检查浮点值是否等于 0 是否安全?

Is it safe to check floating point values for equality to 0?(检查浮点值是否等于 0 是否安全?)

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

问题描述

我知道您通常不能依赖 double 或 decimal 类型值之间的相等性,但我想知道 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 本身似乎很难搞砸,因为它什么都不是.如果你什么都不精确,那它就不再是什么了.

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?

推荐答案

当且仅当 double 变量具有恰好是 0.0 的值(当然,在您的原始代码片段中就是这种情况).这与 == 运算符的语义一致.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".

不安全(因为它不正确)期望某些计算的结果在双精度(或更一般地,浮点)算术中为零每当纯数学中相同计算的结果为零时.这是因为当计算落地时,会出现浮点精度误差——这个概念在数学中的实数算术中是不存在的.

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 does not exist in Real number arithmetics in Mathematics.

这篇关于检查浮点值是否等于 0 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:检查浮点值是否等于 0 是否安全?

基础教程推荐