Here is a segment of C++ code.
#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
double sum1 = 0;
for (double i=0.01f; i<=1.0f; i+=0.01f)
{
sum1 += i;
cout << "i=" << i << endl;
}
cout << sum1 << endl; // sum1=50.5, i=1.00999 99774 247408 < 1.01
// 注意:i精确到小数点后7位
double sum2=0, ii=0.01;
for (ii=0.01; ii<=1.0; ii+=0.01)
{
sum2 += ii;
cout << "ii=" << ii << endl;
}
cout << sum2 << endl; // sum2=49.5, ii=1.00000 00000 00000 7 > 1.0
cout << ii << endl; // 注意:ii精确到小数点后15位
return 0;
}
As comments say, sum1 is not equal to sum2. It is because that float and double type object utilize a 32-bit and a 64-bit quantity to approximate to 0.01 separately. The bit representation of the 32-bit quantity is [0011 1100 0010 0011 1101 0111 0000 1010], while the other one is [0011 1111 1000 0100 0111 1010 1110 0001 0100 0111 1010 1110 0001 0100 0111 1011]. They are both IEEE floating-point representation of 0.01.
With IEEE floating-point format, the first bit string is equal to 0.009999999776483 as a decimal, and the second one is 0.0100000000000000002081668. For this, 1.0 will never be added to sum2.
The precision of float and double is decided by their mantissa. For float, 2^23 = 8388608, there are 6 to 7 significant digits; And for double, 2^52=4503599627370496, there are 15 to 16 significant digits.