[英]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". 我希望总价值约为“ 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 . 这是因为E12
表示E
左边的数字乘以10 12 。
Once you perform the addition of that number and 850.0
, you get the result 一旦执行了该数字和850.0
,就可以得到结果
-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. 通过将小数点一直移到最左侧将其转换为科学计数法后,程序将输出结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.