Float.NaN == Float.NaN [英] Float.NaN == Float.NaN

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

问题描述

为什么这个比较给我'假'?我看着源代码和Float.NaN定义为

Why does this comparison give me 'false'? I looked at the source and Float.NaN is defined as

/** 
 * A constant holding a Not-a-Number (NaN) value of type
 * <code>float</code>.  It is equivalent to the value returned by
 * <code>Float.intBitsToFloat(0x7fc00000)</code>.
 */
public static final float NaN = 0.0f / 0.0f;

编辑:令人惊讶的是,如果我这样做:

surprisingly, if I do this:

System.out.println("FC " + (Float.compare(Float.NaN, Float.NaN)));

它给我 0 。因此 Float.compare()确实认为NaN 是等于其本身!

it gives me 0. So Float.compare() does think that NaN is equal to itself!

推荐答案

因为Java实现了IEEE-754浮点标准,保证任何与 NaN 的比较都会返回false(!= ,它返回true)

Because Java implements the IEEE-754 floating point standard which guarantees that any comparison against NaN will return false (except != which returns true)

这意味着你不能以常用的方式检查浮点数是否为NaN,可以重新解释这两个数字作为int和比较或使用更聪明的解决方案:

That means you can't check in your usual ways whether a a floating point number is NaN, so you could either reinterpret both numbers as ints and compare then or use the much cleverer solution:

def isNan(val):
     return val != val

这篇关于Float.NaN == Float.NaN的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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