0

Possible Duplicate:
Comparing floating point values
How dangerous is it to compare floating point values?

I don't understand, why comparison of real numbers is a bad practice in programming? Of course I understand that real numbers can be represented with some order of accuracy. Can you explain me a weighty reason not to compare this kind of numbers? Examples would be good, the articles are also welcome. Thanks beforehand.

Community
  • 1
  • 1
Sergey Shafiev
  • 4,205
  • 4
  • 26
  • 37
  • 3
    You can read about the floating point accuracy problems here: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems . Comparison of floating point numbers is not always bad, e.g. checking for "less-than" is useful but checking for equality can be dangerous. – gfour Jun 10 '12 at 09:01
  • Just beware to not let them drag you into the dogmatic "never compare floats by equality"-opinion, which is plain rubbish. – Christian Rau Jun 10 '12 at 10:04
  • @ChristianRau - Rules are established for a reason. They help those who lack the experience/judgment to make an informed decision. At some point, one learns that rules CAN be broken in some circumstances, that those rules will never cover all eventualities. However, your statement that the rule in question is "plain rubbish" is just as dogmatic, and just as incorrect. –  Jun 10 '12 at 15:04

1 Answers1

4

From all the questions from under floating-accuracy tag on this site any discussion should probably start with a reference to this question: How dangerous is it to compare floating point values?

And a reference thereof to "What Every Computer Scientist Should Know About Floating Point Arithmetic" by David Goldberg. Here is a short summary.

1. Exact floating point results are not portable

Floating point arithmetic is neither commutative nor associative. IEEE 754 standard that most compilers and platforms follow does not guarantee exact reproducibility of results. Also results will vary on different processors.

2. Floating point comparison does not agree with mathematics

Consider the following statement

  int i = 0; double x = 1.0;
  while (x != 0.0) { x = x/2 ; i++;}

In real numbers this computation should never complete however in floating point it will terminate. The value of i depends on the underlying hardware. Using floating point comparison will make it more difficult to analyze the code.

3. Why then is floating point comparison implemented in hardware?

There are places where exact floating point equality is necessary. One is normalization of floating point numbers.

Community
  • 1
  • 1
Dima Chubarov
  • 16,199
  • 6
  • 40
  • 76