C# 如果与 NaN 的比较总是返回 false,如何将浮点数与 NaN 进行比较?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/639010/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 11:21:10  来源:igfitidea点击:

How can I compare a float to NaN if comparisons to NaN always return false?

c#

提问by Anthony Brien

I have a float value set to NaN (seen in the Watch Window), but I can't figure out how to detect that in code:

我有一个浮点值设置为 NaN(在观察窗口中看到),但我不知道如何在代码中检测它:

if (fValue == float.NaN) // returns false even though fValue is NaN
{
}

采纳答案by John Feminella

You want float.IsNaN(...). Comparisons to NaNalways return false, no matter what the value of the float is. It's one of the quirks of floating points.

你要float.IsNaN(...)NaN无论浮点数的值是什么,比较总是返回 false。这是浮点数的怪癖之一。

That means you can do this:

这意味着你可以这样做:

if (f1 != f1) { // This conditional will be true if f1 is NaN.

In fact, that's exactly how IsNaN() works.

事实上,这正是 IsNaN() 的工作原理。

回答by Jakob Christensen

Try this:

尝试这个:

if (float.IsNaN(fValue))
{
}

回答by Jeff Mc

if(float.isNaN(fValue))
{
}

回答by Tipx

if (fValue.CompareTo(float.NaN) == 0)

Note: I know, the thread is dead.

注意:我知道,线程已死。

回答by Dmitry Fedorkov

In performance-critical code float.IsNaNcould be too slow because it involves FPU. In that case you can use binary mask check (according to IEEE 754 specification) as follow:

在性能关键代码中float.IsNaN可能太慢,因为它涉及 FPU。在这种情况下,您可以使用二进制掩码检查(根据IEEE 754 规范),如下所示:

public static unsafe bool IsNaN (float f)
{
    int binary = *(int*)(&f);
    return ((binary & 0x7F800000) == 0x7F800000) && ((binary & 0x007FFFFF) != 0);
}

It is 5 times faster than float.IsNaN. I just wonder why Microsoft did not implement IsNaNin such way. If you'd prefer not using unsafe code you still can use union-like structure:

它比 快 5 倍float.IsNaN。我只是想知道为什么微软没有IsNaN以这种方式实施。如果您不想使用不安全的代码,您仍然可以使用类似联合的结构:

[StructLayout (LayoutKind.Explicit)]
struct FloatUnion
{
    [FieldOffset (0)]
    public float value;

    [FieldOffset (0)]
    public int binary;
}

public static bool IsNaN (float f)
{
    FloatUnion union = new FloatUnion ();
    union.value = f;

    return ((union.binary & 0x7F800000) == 0x7F800000) && ((union.binary & 0x007FFFFF) != 0);
}

It's still 3 times faster than IsNaN.

它仍然比 快 3 倍IsNaN