comparison of floating point numbers with equality operator. possible loss of precision while rounding values
double值由外部传入
private void Compare(double value) { string text; if (value != 0) //小数位后保留2位 { //小数点后保留2位小数 text = string.Format("{0:0.00}", value); } else { text = "0"; } }
Nope it's perfectly legal if you are only going to compare against 0 as the right side of comparison will automatically casted to double. On the other hand, it would yield all the round-off errors if you where to compare against == 0.10000001
You are better or reading the discussion about float to 0 comparison here: C#.NET: Is it safe to check floating point values for equality to 0?
Also this discussion is very informative about weird precision problems on floats: Why the result is different for this problem?
i.e. below will yield false:
double d1 = 1.000001; double d2 =0.000001;
Console.WriteLine((d1-d2)==1.0);
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, needless to say, does not exist in Real number arithmetics in Mathematics.
Well, how close do you need the value to be to 0? If you go through a lot of floating point operations which in "infinite precision" might result in 0, you could end up with a result "very close" to 0.
Typically in this situation you want to provide some sort of epsilon, and check that the result is just within that epsilon:
if (Math.Abs(something) < 0.001)
The epsilon you should use is application-specific - it depends on what you're doing.
Of course, if the result should be exactly zero, then a simple equality check is fine.
作者:Chuck Lu GitHub |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2014-09-22 如何将一个Winform嵌入到一个Control当中