简体   繁体   English

比较浮点值

[英]Comparing floating point values

I just read a statement about the floating point value comparison 我刚刚阅读了有关浮点值比较的声明

Floating point values shall not be compared using either the == or != operators. 不能使用==或!=运算符比较浮点值。 Most floating point values have no exact binary representation and have a limited precision. 大多数浮点值没有精确的二进制表示,并且精度有限。

If so what is the best method for comparing two floating point values? 如果是这样,比较两个浮点值的最佳方法是什么?

The following extension methods may be useful to implement Kevin's suggestion: 以下扩展方法可能有助于实现Kevin的建议:

public static bool IsEqualTo(this double a, double b, double margin)
{
    return Math.Abs(a - b) < margin;
}

public static bool IsEqualTo(this double a, double b)
{
    return Math.Abs(a - b) < double.Epsilon;
}

So now you can just do: 所以现在你可以这样做:

if(x1.IsEqualTo(x2)) ...
if(x1.IsEqualTo(x2, 0.01)) ...

Just change the IsEqualTo to a more appropriate name, or change the default margin to anything better than double.Epsilon , if needed. 只需将IsEqualTo更改为更合适的名称,或将默认边距更改为double.Epsilon (如果需要)。

Generally floating point numbers should be compared using a construct like 通常,浮点数应使用类似的构造进行比较

if( abs((x1 - x2) < 0.001) )

The reason for the warning you quoted is you may have two methods of calculating something, and they may be equal if you had no rounding error, but the rounding error makes them slightly different. 你引用警告的原因是你可能有两种计算方法,如果没有舍入误差它们可能相等,但舍入误差会使它们略有不同。

"Best method" depends on the circumstances of why you want to compare the numbers. “最佳方法”取决于您想要比较数字的情况。 In general, if you think you want to check if 2 floating points numbers are equal, you are doing something wrong. 一般来说,如果您认为要检查2个浮点数是否相等,那么您做错了。

Floating point numbers are supposed to be used to represent real values, in both senses of the word. 浮点数应该用于表示单词的两种意义上的实际值。 Is this object the same length as this other object? 该对象的长度是否与其他对象相同? Well, they may look the same length, but if you get a good enough measuring device, you can always find a difference. 好吧,它们的长度可能相同,但如果你得到一个足够好的测量设备,你总能找到差异。 Similarly, two floating point numbers are never equal, unless they are measuring the same thing, and have been processed in exactly the same way. 类似地,两个浮点数永远不会相等,除非它们测量相同的东西,并且已经以完全相同的方式处理。 Other than that, it's just a rounding error somewhere in the system. 除此之外,它只是系统中某处的舍入错误。

You might want to check that they are close, (closer than a certain threshold) as the other answers have suggested, but not equal. 您可能想要检查它们是否接近,(接近某个阈值)正如其他答案所建议的那样,但不相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM