gpt4 book ai didi

c# - C# 的浮点比较函数

转载 作者:IT王子 更新时间:2023-10-29 03:44:04 26 4
gpt4 key购买 nike

有人可以指出(或展示)C# 中一些用于比较浮点值的通用浮点比较函数吗?我想为 IsEqualIsGreaterIsLess 实现函数。我也只关心 double 而不是花车。

最佳答案

编写一个有用的通用 float IsEqual 是非常非常困难的,如果不是完全不可能的话。对于 a==0,您当前的代码将严重失败。该方法在这种情况下应该如何表现实际上是一个定义问题,并且可以说代码最好针对特定领域用例进行定制。

对于这种事情,您真的非常需要一个好的测试套件。这就是我为 The Floating-Point Guide 做的,这就是我最后想到的(Java代码,应该很容易翻译):

public static boolean nearlyEqual(float a, float b, float epsilon) {
final float absA = Math.abs(a);
final float absB = Math.abs(b);
final float diff = Math.abs(a - b);

if (a == b) { // shortcut, handles infinities
return true;
} else if (a == 0 || b == 0 || absA + absB < Float.MIN_NORMAL) {
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * Float.MIN_NORMAL);
} else { // use relative error
return diff / (absA + absB) < epsilon;
}
}

您还可以找到 the test suite on the site .

附录:在 c# 中用于 double 的相同代码(如问题中所问)

public static bool NearlyEqual(double a, double b, double epsilon)
{
const double MinNormal = 2.2250738585072014E-308d;
double absA = Math.Abs(a);
double absB = Math.Abs(b);
double diff = Math.Abs(a - b);

if (a.Equals(b))
{ // shortcut, handles infinities
return true;
}
else if (a == 0 || b == 0 || absA + absB < MinNormal)
{
// a or b is zero or both are extremely close to it
// relative error is less meaningful here
return diff < (epsilon * MinNormal);
}
else
{ // use relative error
return diff / (absA + absB) < epsilon;
}
}

关于c# - C# 的浮点比较函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3874627/

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