它是安全的检查平等的浮点值设置为0? [英] Is it safe to check floating point values for equality to 0?

查看:129
本文介绍了它是安全的检查平等的浮点值设置为0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你不能依靠双精度或十进制类型的值之间的相等正常,但我想知道如果0是一种特殊情况。

I know you can't rely on equality between double or decimal type values normally, but I'm wondering if 0 is a special case.

虽然我能理解0.00000000000001和0.00000000000002,0之间的IM precisions本身似乎pretty努力陷入困境,因为它只是没有。如果你就没事IM precise,这不是什么了。

While I can understand imprecisions between 0.00000000000001 and 0.00000000000002, 0 itself seems pretty hard to mess up since it's just nothing. If you're imprecise on nothing, it's not nothing anymore.

但我不知道很多关于这个话题,所以它不是我说。

But I don't know much about this topic so it's not for me to say.

double x = 0.0;
return (x == 0.0) ? true : false;

将始终返回true?

Will that always return true?

推荐答案

安全以期望的比较将返回真正如果和只有在双变量的值完全 0.0 (在你原来的code段是当然的情况下,)。这与 == 操作符的语义一致。 A == b 办法 A 等于 B

It is safe to expect that the comparison will return true if and only if the double variable has a value of exactly 0.0 (which in your original code snippet is, of course, the case). This is consistent with the semantics of the == operator. a == b means "a is equal to b".

不安全(因为它的不正确)的期望,一些计算的结果将是零双(或者更一般地说,浮点)只要算术在纯数学同样的计算结果是零。这是因为当计算进入地面,浮点precision错误显示。 - 一个概念,它不用说,不实数算术存在数学

It is not safe (because it is not correct) to expect that the result of some calculation will be zero in double (or, more generally, floating point) arithmetics whenever the result of the same calculation in pure Mathematics is zero. This is because when calculations come into the ground, floating point precision error appears - a concept which, needless to say, does not exist in Real number arithmetics in Mathematics.

这篇关于它是安全的检查平等的浮点值设置为0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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