检查两个float / double值是否相等

编程入门 行业动态 更新时间:2024-10-26 22:18:48
本文介绍了检查两个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值是否相等

本文发布于:2023-11-08 13:25:05,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两个   float   double

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!