double precision confusion =P

Heya, first time poster & big fan =]

I'm taking an intro c++ course and have gotten to the first real stumbling block in understanding.

There are some strange rounding problems that seem to crop up with double arithmetic and have found some great resources about floating point #'s like http://en.wikipedia.org/wiki/Floating_point and http://www.cplusplus.com/articles/Nb07M4Gy/ but haven't really found an easy answer for why this program wouldn't run as expected or whats going on with the math to make this "wonky". The professor may have glossed over this it b/c it's outside the scope of the class but any basic explanations of whats going on here or a point in the right direction would be much appreciated.

Thank you for your time!!!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <iomanip>
#include <iostream> 
using namespace std; 
  
int main() 

{ 
  double sum = 0;
  
  for (int i = 0; i < 10; i++)
  {
    double x = .126;
    sum += x;
   
    cout << i << "  " << sum << "\n";
  }  
  
  if (sum == 1.26)
    cout << "\n" << sum << " = 1.26" << endl;
  else
    cout << "\n" << sum << " != 1.26" << endl << endl;
  
    
  sum = 0;
      
  for (int i = 0; i < 10; i++)
  {
    double x = .125;
    sum += x;
   
    cout << i << "  " << sum << "\n";
  }  
  
  if (sum == 1.25)
    cout << "\n" << sum << " = 1.25" << endl;
  else
    cout << "\n" << sum << " != 1.25" << endl;  

  return 0; 
} 



0 0.126
1 0.252
2 0.378
3 0.504
4 0.63
5 0.756
6 0.882
7 1.008
8 1.134
9 1.26

1.26 != 1.26

0 0.125
1 0.25
2 0.375
3 0.5
4 0.625
5 0.75
6 0.875
7 1
8 1.125
9 1.25

1.25 = 1.25
Essentially, 1.25 has an exact representation in double precision format whereas 1.26 does not.

Try it out yourself:
http://www.binaryconvert.com/convert_double.html
Topic archived. No new replies allowed.