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

