比较浮点值 [英] Comparing floating point values

查看:202
本文介绍了比较浮点值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚看了一个关于浮点值比较报表

I just read a statement about the floating point value comparison

浮动无论使用==或点值不能拿来比较!=   运营商。   大多数浮点值没有确切的二进制重新presentation并有   有限的precision。

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:

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)) ...

只要改变 IsEqualTo 来一个更合适的名称,或者更改默认的利润率比 double.Epsilon ,如果需要的话。

Just change the IsEqualTo to a more appropriate name, or change the default margin to anything better than double.Epsilon, if needed.

这篇关于比较浮点值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆