算术表达式计算 6.135157E-6 而不是零

发布于 2025-01-02 19:35:50 字数 237 浏览 5 评论 0原文

我的应用程序中的某处有以下代码

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦旅人picnic 2025-01-09 19:35:50

问题是 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.

心的憧憬 2025-01-09 19:35:50

计算机中的浮点计算并不准确。您应该阅读有关浮点算术的内容以防止此类错误。

Floating point calculations in computers are not accurate. You should read something about floating point arithmetics to prevent such errors.

呆头 2025-01-09 19:35:50

问题不在于值,而在于向用户的显示。

我假设您正在将其转换为字符串。 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

示例:

NumberFormat formater = NumberFormat.getNumberInstance()
formatter.setMaximumFractionDigits(4);
formater.format(myMethod(-273.15))

现在您应该得到 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 :

NumberFormat formater = NumberFormat.getNumberInstance()
formatter.setMaximumFractionDigits(4);
formater.format(myMethod(-273.15))

Now you should get 0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文