Addition calculation error of double-precision floating point number and its preliminary method to avoid it

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.