比较浮点 0
如果 foo 是 float 类型,以下表达式是否有效/推荐?
(0.0f == foo * float(0))
无论 foo 的值如何,它都会具有预期的(数学)值吗?
C++ 标准是否定义了行为,还是特定于实现的?
If foo is of float type, is the following expression valid/recommended?
(0.0f == foo * float(0))
Will it have the expected (mathematical) value regardless of foo's value?
Does the C++ standard defines the behavior or is it implementation specific?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
嗯,首先,这实际上并不是 C++ 标准的问题。相反,问题在于你的浮点模型标准(最有可能是 IEEE)。
对于 IEEE 浮点数,这可能是安全的,因为
float(0)
应该得到与 0.0f 相同的数字,并且乘以任何其他数字也应该是 0.0f。真正不安全的是执行其他浮点运算(例如:使用非整数进行加法和减法)并根据 0.0f 检查它们。
Well, first off it isn't really a matter of the C++ standard. Rather what is at issue is your floating-point model standard (most likely IEEE).
For IEEE floats, that is probably safe, as
float(0)
should result in the same number as 0.0f, and that multiplied by any other number should also be 0.0f.What isn't really safe is doing other floating point ops (eg: adds and subtracts with non-whole numbers) and checking them against 0.0f.
正如其他人已经提到的,NaN 和 Infinites 可能会搞砸这种比较。
然而,还有进一步的陷阱:在 C++ 中,您不能依赖于 float 类型的编译时表达式来比较等于运行时计算的相同表达式。
原因是 C++ 允许以任意方式扩展 fp 计算的精度。示例:
使用一个特定编译器的结果:
Cheers & hth.,
– 阿尔夫
NaNs and Infinites can screw up such comparisions, as others have already mentioned.
However, there is further pitfall: in C++ you can not rely on a compile time expression of float type, comparing equal to the same expression evaluated at run time.
The reason for that is that C++ allows extended precision for fp computations, in any willy-nilly way. Example:
Results with one particular compiler:
Cheers & hth.,
– Alf
AFAIK,这不一定,它也可能最终非常接近 0。
通常最好与 epsilon 进行比较。我使用这样的函数来进行此类比较:
AFAIK, It won't necessarily, it could also end up very close to 0.
It is generally best to compare against an epsilon. I use a function like this for doing such comparisons:
通过该特定语句,您可以非常确定结果将为
0
并且比较为true
- 我不认为 C++ 标准实际上规定了它,但任何合理的浮点类型的实现将有0
像这样工作。然而,对于大多数其他计算,结果不能完全等于数学上正确结果的文字:
阅读浮点指南,了解详细说明以及操作方法与预期值正确比较。
With that particular statement, you can be pretty sure the result will be
0
and the comparison betrue
- I don't think the C++ standard actually prescribes it, but any reasonable implementation of floating point types will have0
work like that.However, for most other calculations, the result cannot be expected to be exactly equal to a literal of the mathematically correct result:
Read The Floating-Point Guide for detailed explanations and how to do comparisons with expected values correctly.
我刚刚在 msdn 中读到这篇关于 VisualStudio 中 /fp 选项的文章
链接文本
I just read this article in msdn about the /fp option in VisualStudio
link text