Addition calculation error of double-precision floating point number and its preliminary method to avoid it
I first found the calculation error in MySQL's sum function. After analysis, I thought it may be related to double-precision floating-point numbers.
# Include <stdio. h>
Main ()
{
Char STR [256];
Double X = 9999999999.00;
Double S = 0.0;
Double X1 = 99999999.99;
Double S1 = 0.0;
Int I;
For (I = 0; I <8192; I ++ ){
S + = X;
}
Printf ("% 18.2lf", S );
For (I = 0; I <8192; I ++)
{
S1 + = x1;
}
Printf ("% 18.2lf", S1 );
S1 = x1 * 8192.00;
Printf ("% 18.2lf/N", S1 );
}
Compile and run under Windows and Unix respectively, and the results are the same.
81919999991808.00 819199999918.02 819199999918.08
This shows that the addition of double-precision floating-point numbers has a large error after the decimal point, while multiplication is better.
I initially came up with two solutions, immature and I have never tried other languages. please correct me.
Solution 1:
Avoid using double.
For example, write in VB using the currency type.
Private sub commandementclick ()
Dim I as integer
Dim s as double
Dim X as double
Dim SC as currency
Dim XC as currency
X = 99999999.99
S = 0
For 1 to 8192
S = S + x
Next I
XC = 99999999.99
SC = 0
For 1 to 8192
SC = SC + XC
Next I
Msgbox S & "" & SC
End sub
Result: 819199999918.017 819199999918.08
Solution 2:
You do not need a decimal point when adding it.
For example:
99999999.99 move the decimal point to the right two places during the Join Operation
Use 9999999999 for concatenation. After the result is obtained, the decimal point is shifted to two places.