
LOGO-L> Floating point trick once more
Sorry, but my mailing program is trying to decide, what should be published and what shouldn't.
So once again:
Do not blame Logo for bad addition.
Each computation system based on floating point numbers with finite length will make an error in such operation. In fact we can trace this error with a sheet of paper. Let's assume that we have a calculator with 10 decimal digit. Where both number are near, it is no error in addition:
0.000000012
+0.000000023
--------------------
=0.000000035 OK.
But when one number is substantially greater, we lose part of accuracy:
10.00000001
+ 0.000000023
--------------------
=10.00000003 BAD - we've lost 0.000000003
We may also see additions, which give no effect. For example 1000000000.1+0.0000001 give as the result 1000000000.1
We can use this effect to make some trick. Let's take a look on following procedure
(In this example global makes are applied intentionally, Yehuda - please don't extract them this time)
(to xsum)
make "a0 :a
make "a :a0 + :delta
make "b1 :a0 - :a
make "b2 :b1 + :delta
make "b :b2 + :b
(end)
You may say, that :a0 + :delta - :a0 - :delta equals 0. This is true in arithmetic, but not on floating point computation. Small difference will be gathered in variable :b. Please repeat xsum 1640 times with :a0=0 :delta=0.02 (all other variables should start with 0 also) and take :a+:b as the result. You will get 32.8 exactly. With :delta about 0.000000001 this effect is even stronger.
This algorithm of adding with error correction is well known in differential equation solving. For the best results you should look for some professional solutions - for example Runge-Kutta method.
Best regards
Andrzej B.
---------------------------------------------------------------