Monday, February 19, 2018

math - Real numbers comparison










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.



Answer



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.


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...