liveBook · Manning

Heron approximation

As explained in Modern C

The Heron approximation is an iterative numerical method for computing the multiplicative inverse of a number.

A compact inverse calculation

Given a = 34.0 and an initial x = 0.5: while (fabs(1.0 - a*x) >= eps) { x *= (2.0 - a*x); } Each pass refines x until a*x is sufficiently close to 1.0. The resulting x approximates 1/a. section 3.2

TAKEAWAY: Heron approximation is an iterative numerical method whose update x *= (2.0 - a*x) improves an estimate of a number’s multiplicative inverse. section 3.2

The iteration can be expressed in several C control-flow forms:

  • A while loop tests the stopping condition before each pass, so it may execute zero times. section 3.2
  • A do loop performs one refinement before testing whether the estimate is close enough. section 3.2
  • An unbounded while or for loop can separate product calculation, stopping with break, and refinement. section 3.2
   #include <tgmath.h>

   double const eps = 1E-9;            // Desired precision
   ...
   double const a = 34.0;
   double x = 0.5;
   while (fabs(1.0 - a*x) >= eps) {    // Iterates until close
     x *= (2.0 - a*x);                 // Heron approximation
   }


!@%STYLE%@!
{"css":"{\"css\": \"font-weight: bold;\"}","target":"[[{\"line\":0,\"ch\":4},{\"line\":0,\"ch\":11}],[{\"line\":2,\"ch\":3},{\"line\":2,\"ch\":15}],[{\"line\":4,\"ch\":3},{\"line\":4,\"ch\":15}],[{\"line\":2,\"ch\":3},{\"line\":2,\"ch\":15}],[{\"line\":4,\"ch\":3},{\"line\":4,\"ch\":15}],[{\"line\":2,\"ch\":3},{\"line\":2,\"ch\":9}],[{\"line\":4,\"ch\":3},{\"line\":4,\"ch\":9}],[{\"line\":5,\"ch\":3},{\"line\":5,\"ch\":9}],[{\"line\":6,\"ch\":3},{\"line\":6,\"ch\":8}],[{\"line\":6,\"ch\":10},{\"line\":6,\"ch\":14}]]"}
!@%STYLE%@!

Browse the complete compact implementation, including the precision threshold, floating-point input, convergence test, and Heron update. section 3.2

How Modern C covers it

How deep it goes
Explains the update and stopping test with code, but defers the numerical derivation.
Examples
Uses a = 34.0, x = 0.5, an epsilon threshold, and complete C listings with sample inverse results.
What you can do after
Apply it via C loop constructs to compute approximate multiplicative inverses with a chosen precision threshold.
How it connects
Connects multiplicative inverse, floating-point arithmetic, while loops, do-while loops, and break statements.

Also explained in

Compare how 2 books explain Heron approximation →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Modern C. The section links point to the parts of the book it draws on.