Question
I have a problem running a loop in the macro below:
Synopsis
Resolving Floating Point round-off errors in a scheme macro
Solution
(do ( (K -1.6 (+ K 0.2) ) )
( (> K 0) K )
(display K)
(newline)
)
The value of K should start at -1.6 and end at 0; however, the last value of K is always -2.77555756156289e-016. Is there any way to make the last count value of K exactly equal to zero?
--------------------------------------------------------------------
The strange value that appears instead of the 0.0 that you expect is a result of a floating point error. Please see the following Wikipedia webpage that discusses the floating point in detail:
http://en.wikipedia.org/wiki/Floating_point
The trick to resolve this issue is to have the loop count in integers, and then multiply or divide within the loop to get the proper value for the variable, as integers are not subject to this floating point issue. The macro below achieves the intended result:
(do ( (Ktemp -8 (+ Ktemp 1) ) )
( (> Ktemp 0) Ktemp )
(define K (/ Ktemp 5))
(display K) (newline)
)