gawk: Errors accumulate
1
1 15.4.1.3 Errors Accumulate
1 ..........................
1
1 The loss of accuracy during a single computation with floating-point
1 numbers usually isn't enough to worry about. However, if you compute a
1 value that is the result of a sequence of floating-point operations, the
1 error can accumulate and greatly affect the computation itself. Here is
1 an attempt to compute the value of pi using one of its many series
1 representations:
1
1 BEGIN {
1 x = 1.0 / sqrt(3.0)
1 n = 6
1 for (i = 1; i < 30; i++) {
1 n = n * 2.0
1 x = (sqrt(x * x + 1) - 1) / x
1 printf("%.15f\n", n * x)
1 }
1 }
1
1 When run, the early errors propagate through later computations,
1 causing the loop to terminate prematurely after attempting to divide by
1 zero:
1
1 $ gawk -f pi.awk
1 -| 3.215390309173475
1 -| 3.159659942097510
1 -| 3.146086215131467
1 -| 3.142714599645573
1 ...
1 -| 3.224515243534819
1 -| 2.791117213058638
1 -| 0.000000000000000
1 error-> gawk: pi.awk:6: fatal: division by zero attempted
1
1 Here is an additional example where the inaccuracies in internal
1 representations yield an unexpected result:
1
1 $ gawk 'BEGIN {
1 > for (d = 1.1; d <= 1.5; d += 0.1) # loop five times (?)
1 > i++
1 > print i
1 > }'
1 -| 4
1