Welcome, Guest. Please login or register.

Author Topic: while() with float ?  (Read 3036 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Cymric

  • Hero Member
  • *****
  • Join Date: Nov 2002
  • Posts: 1031
    • Show all replies
Re: while() with float ?
« on: February 17, 2006, 03:06:07 PM »
It is very important that you realise what goes on. There's two issues to come to terms with.

First, when you write something like 'if (some_val==(float)1.0))' then what happens is that the bit pattern of some_val is compared to the bit pattern representing (float)1.0. If they are off by just one bit, the entire comparison breaks down.

Second, floating point arithmetic is not exact. To us humans, the outcome of a calculation like 1.0 - 0.001 is clear: 0.999. But not so in computer terms, which have to represent such numbers with the sum of certain fractions (1/2, 1/4, 1/8, and so forth). In other words, the answer of the above calculation might very well be 0.998999999. That may not look like a major difference, but if you count on it being 0.999 exactly, you have a problem.

The moral of the story is (and trust me, I've learned this the very hard way) that you must NEVER do straightforward compares to floating point numbers unless you are using exact or adaptive arithmetic. In other words: you must rewrite your loop so it doesn't rely on a comparison to (float)1.0. Either use Piru's tactic to add a small 'fudge factor', or rewrite the routine so it uses exact or adaptive arithmetic, or don't use floating points at all. Those are your options. And no, switching to double, or even double double will not help.

Yes, that probably sucks. Welcome to the wonderful world of approximate mathematics.
Some people say that cats are sneaky, evil and cruel. True, and they have many other fine qualities as well.