检查两个float / double值是否相等 [英] Check two float/double values for exact equality

查看:238
本文介绍了检查两个float / double值是否相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是比较两个浮点值精确相等的优雅,可读和非冗长的方式?

听起来很简单,它是一个邪恶的问题。 == 操作符不能完成NaN的工作,对零也有特殊的处理:

 (+ 0.0 == -0.0) - > true 
Double.NaN == Double.NaN - >假

但是我想确定两个值是否完全相同(但我不是不是关心不同的NaN模式,所以NaN ==任何其他的NaN - > true)。
$ b (b)


 / code> 

有没有更好的方法来写这个(并且使意图显而易见)?

你知道,已经是最好的方式了。它清楚地表明您对该值的 bitwise 表示感兴趣。你恰好将这些位转换为 long 作为一个方便的64位类型,它没有任何时髦的行为。



如果您不希望它在代码库中频繁出现,只需添加一个方法来包装它:

  public static boolean bitwiseEqualsWithCanonicalNaN(double x,double y){
return Double.doubleToLongBits(x)== Double.doubleToLongBits(y);

code


$ b请注意,根据你的问题,这不是不是区分不同的NaN值。如果您想在稍后的日期执行此操作,则需要使用 Double.toRawLongBits


What is an elegant, readable and non-verbose way of comparing two floating point value for exact equality?

As simple as it may sound, its a wicked problem. The == operator doesn't get the job done for NaN and also has special treatment for zero:

(+0.0 == -0.0) -> true
Double.NaN == Double.NaN -> false

But I want to determine if two values are exactly the same (but I do not care for different NaN patterns, so any NaN == any other NaN -> true).

I can do this with this ugly Monster piece of code:

Double.doubleToLongBits(a) == Double.doubleToLongBits(b)

Is there a better way to write this (and make the intent obvious)?

解决方案

What you've got is already the best way of doing it, I'd say. It makes it clear that you're interested in the bitwise representation of the value. You happen to be converting those bits to long as a convenient 64-bit type which doesn't have any funky behaviour.

If you don't want it appearing frequently in your codebase, just add a method to wrap it:

public static boolean bitwiseEqualsWithCanonicalNaN(double x, double y) {
    return Double.doubleToLongBits(x) == Double.doubleToLongBits(y);
}

Note that as per your question, this does not differentiate between different NaN values. If you wanted to do this at a later date, you'd need to use Double.toRawLongBits.

这篇关于检查两个float / double值是否相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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