算术表达式计算 6.135157E-6 而不是零
我的应用程序中的某处有以下代码
float private myMethod(float c){
result = (float) (c+273.15);
}
,当“c”获得类似 -273.1455 的值时,结果非常接近于零,如 0.0044。
但是当它得到值 -273.15 时,我得到这个而不是零: 6.1035157E-6
为什么会发生这种情况?
I have the below code somewhere in my app
float private myMethod(float c){
result = (float) (c+273.15);
}
When "c" gets the value something like -273.1455 the result is something very near to zero like 0.0044.
But when it gets the value -273.15 i get this instead of zero: 6.1035157E-6
Why does this happen?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是 273.15 是双精度数,而不是浮点数,它们都不能准确表示 273.15。然而,由于它们具有不同的精度,因此它们实际上会四舍五入存储不同的数字。当加法完成后,c 被转换为 double,它将能够存储 273.15 的浮点表示形式。所以现在你有两个具有几乎相同值的双精度值,并且差异将不为零。
为了获得“更可预测”的结果,请使用 273.15f 确保计算过程中存在浮动。这应该可以解决这个问题,但是您需要做的是阅读二进制浮点算术以及它与我们在学校教授的十进制算术有何不同。
关于浮点的 Wiki 是一个很好的起点。
The problem is that 273.15 is a double, not a float, and neither of them can represent 273.15 exactly. However, since they have different precision they will round actually store different numbers. When the addition is done the c is converted to a double which will be able store the float representation of 273.15. So now you have two doubles with almost the same value and the difference will be non zero.
To get "more predictable" result, use 273.15f to ensure you have floats through the calculations. That should solve this problem but what you need to do is to read up on binary floating point arithmetics and how that differs from decimal arithmetic that we are taught in school.
Wiki on floating point is a good place to start.
计算机中的浮点计算并不准确。您应该阅读有关浮点算术的内容以防止此类错误。
Floating point calculations in computers are not accurate. You should read something about floating point arithmetics to prevent such errors.
问题不在于值,而在于向用户的显示。
我假设您正在将其转换为字符串。 http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Double.html#toString(double)
要显示正确的值,请使用 NumberFormat 类 http://docs.oracle.com/javase/1.4 .2/docs/api/java/text/NumberFormat.html
示例:
现在您应该得到 0。
The problem is not with the value, but with the display to the user.
I'm assuming you are converting it into a String. The way this is done is detailed in http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Double.html#toString(double)
To Display a correct value use the NumberFormat class http://docs.oracle.com/javase/1.4.2/docs/api/java/text/NumberFormat.html
Example :
Now you should get 0.