wtf?!

Hi guys! I have this simple code
1
2
3
4
5
6
7
8
9
10
   #include <iostream>
   using namespace std;
   int main() {
   
           for( float f = -0.8f; f <= 0.8f; f+=0.04f )
                   cerr << f << '\n';
   
   
   }


When I run this code ( compiled with g++ ) , the output is

-0.8
-0.76
-0.72
-0.68
-0.64
-0.6
-0.56
-0.52
-0.48
-0.44
-0.4
-0.36
-0.32
-0.28
-0.24
-0.2
-0.16
-0.12
-0.0799999
-0.0399999
5.96046e-08
0.0400001
0.0800001
0.12
0.16
0.2
0.24
0.28
0.32
0.36
0.4
0.44
0.48
0.52
0.56
0.6
0.64
0.68
0.72
0.76


How you see in lines 19-23 the output is in other format. Whats the reason ???
Why it's doing that only when it's closer to zero?
The same result is with double.


Best regards

-holtaf
closed account (1yR4jE8b)
It's because floating point numbers cannot be represented exactly in binary:

Essential Read:
http://download.oracle.com/docs/cd/E19957-01/806-3568/ncg_goldberg.html
Yes, and as such, floating point arithmetic is subject to error. float is 32 bit. Changing float to double (64bit) yields the following output, which is much closer to zero:

-0.8
-0.76
-0.72
-0.68
-0.64
-0.6
-0.56
-0.52
-0.48
-0.44
-0.4
-0.36
-0.32
-0.28
-0.24
-0.2
-0.16
-0.12
-0.08
-0.04
1.249e-016
0.04
0.08
0.12
0.16
0.2
0.24
0.28
0.32
0.36
0.4
0.44
0.48
0.52
0.56
0.6
0.64
0.68
0.72
0.76

(Built with MSVC++10)
Last edited on
Topic archived. No new replies allowed.