简体   繁体   中英

Floating point calculation error in Java

Help, I got a problem when adding double value with negative number
A sample program to show the problem:

    double newX = 850.0;
    double delta = -1.6994427191177073E12;
    double total = delta + newX;
    System.out.println("newX:" + newX);
    System.out.println("delta:" + delta);
    System.out.println("total:" + total);

but the given output is:

 newX:850.0
 delta:-1.6994427191177073E12
 total:-1.6994427182677073E12

I would expect the total value to be around "848.30055729". How to handle this calculation?

Regards,

Dennis

The computation is correct.

Lets start by converting your number from scientific notation

-1.6994427191177073E12

to decimal fixed-point notation:

-1699442719117.7073

This is because E12 means that the number to the left of E is multiplied by 10 12 .

Once you perform the addition of that number and 850.0 , you get the result

-1699442718267.7073

Once you convert it to scientific notation by bringing the decimal point all the way to the left, you get the result printed by your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM