Next: Setting precision, Previous: Getting Accuracy, Up: FP Math Caution [Contents][Index]
Instead of arbitrary-precision floating-point arithmetic, often all you need is an adjustment of your logic or a different order for the operations in your calculation. The stability and the accuracy of the computation of pi in the earlier example can be enhanced by using the following simple algebraic transformation:
(sqrt(x * x + 1) - 1) / x ≡ x / (sqrt(x * x + 1) + 1)
After making this change, the program converges to pi in under 30 iterations:
$ gawk -f pi2.awk -| 3.215390309173473 -| 3.159659942097501 -| 3.146086215131436 -| 3.142714599645370 -| 3.141873049979825 … -| 3.141592653589797 -| 3.141592653589797