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 是否安全?
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
