Why in some programming languages the expression in title evaluates to true? I've tried it in php, ruby and python.
Asked
Active
Viewed 3,639 times
5
Samuel Liew
- 72,637
- 105
- 156
- 238
Eimantas
- 48,240
- 16
- 132
- 164
-
13http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems – Ignacio Vazquez-Abrams Dec 31 '10 at 16:21
-
1possible duplicate of [Is JavaScript's Math broken?](http://stackoverflow.com/questions/588004/is-javascripts-math-broken) And about a hundred other questions. – dan04 Dec 31 '10 at 16:23
-
The accepted answer to that one is marvelous. http://stackoverflow.com/questions/588004/is-javascripts-math-broken/588014#588014 – Paul Tomblin Dec 31 '10 at 16:25
-
1It evaluates to true because it is true (when 0.1, etc are floating-point literals). – Stephen Canon Dec 31 '10 at 16:36
3 Answers
2
double TOLERANCE < 1.0E-10;
if(fabs(0.1+0.7-0.8)< TOLERANCE)
{
std::cout << "0.1 + 0.7 == 0.8" << std::endl;
}
else
{
std::cout << "0.1 + 0.7 != 0.8" << std::endl;
}
Cesar A. Rivas
- 1,359
- 1
- 10
- 13
0
Because of internal interpretation of floating-point numbers, they do not exactly equal to what you have wrote.
Nickolay Olshevsky
- 12,926
- 1
- 30
- 44