gpt4 book ai didi

c# - 比较 float 的总和

转载 作者:行者123 更新时间:2023-12-01 05:48:02 25 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





Is floating point math broken?

(31 个回答)


去年关闭。




我在 Unity 中运行此代码(带有 .Net 4.x 的 Mono 后端)

float a = 0.42434249394294f;
float b = 1 - a;
float sum = a + b;
bool compare1 = (a + b) >= 1f;
bool compare2 = sum >= 1f;

在调试(使用 Visual Studio)中, compare1falsecompare2true .

这是怎么回事?为什么最后两行不同?我认为 sum == a + b .

最佳答案

您遇到了一个非常常见的数值精度错误,称为 round-off error .对浮点值求和时,需要包含容错。这种错误是所有编程语言中浮点数学运算所固有的。

您的代码应更改为如下所示:

const float errorTolerance = 0.000001f;
float target1 = a + b;
float target2 = sum;
bool compare1 = Math.Abs(target1 - 1f) <= errorTolerance;
bool compare2 = Math.Abs(target2 - 1f) <= errorTolerance;

还要注意在 c# 中使用浮点数,它是一个单精度浮点数,精度只有 6-7 位有效数字。

关于c# - 比较 float 的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60471494/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com