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 是否安全?
基础教程推荐
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01