in reply to Re^3: Floating Point Errors: How and Why to Avoid Adding and Subtracting Varying Numbers
in thread Floating Point Errors
That's a fairly contrived example.
Yes, indeed. It was carefully contrived in a fair manner to demonstrate the problem with the "better" code. (:
The better_average loses here because of compounded errors in float division.
And it appears that it demonstrated the problem quite successfully to you. Yes, you have described exactly why the "better" code is actually worse. Doing the division once eliminates the possibility of accumulating errors from doing the division over and over again (and is more efficient).
I tried using random numbers instead, and I found them more or less equivalent.
Yes, floating point is carefully designed so that in most cases it mostly "just works". It is usually required that one carefully contrive the example to demonstrate the weakness in a floating point calculation. And you need to pay attention to how far off things can get, not how often near-single-bit errors happen to benefit one method vs the other.
The first sentence of ikegami's is true: It can be good to avoid adding numbers of much different magnitudes. (It is even better to avoid getting a small-magnitude result by subtracting two, much larger numbers.) But his example doesn't appear to have anything to do with that advice.
A better example of that is adding up a huge list of numbers. You can get a more accurate total if you add up the small-magnitude numbers before adding in the big-magnitude numbers. Does that mean you should sort before adding up any list of numbers? Probably not. Most of the time it doesn't make much difference. But if you know you are going to need to sum up a few really large numbers and a ton of small numbers, then you certainly might want to save the big numbers for last.
I do some similar tricks in Math::BigApprox. I also do some tricks to deal with floating-point numbers that are nearly equal (the FAQest "gotcha" with floating-point calculations).
- tye
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^5: Floating Point Errors: How and Why to Avoid Adding and Subtracting Varying Numbers (contriving)
by kyle (Abbot) on May 29, 2008 at 03:10 UTC | |
by tye (Sage) on May 29, 2008 at 06:40 UTC |