Is it safe to check floating point values for equality to 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 是否安全?


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01