C- ceil/float founding to int保证
我想知道由于浮点不准确而导致这样的代码是否会不正确:
#include <math.h>
// other code ...
float f = /* random but not NAN or INF */;
int i = (int)floorf(f);
// OR
int i = (int)ceilf(f);
对这些价值有任何保证吗?如果我有一个良好的f
(不是nan或inf),则i
始终是圆形的整数,无论是哪种方式。
我可以想象一个情况(对于规格/实现不好的情况),您获得的值是低于真实值的值,而不是高于/相等的值,但实际上更接近。然后,当您将其截断时,它实际上将圆形为下一个较低的值。
在我看来,鉴于整数可以是IEEEE754浮点的确切值,但我不知道float
是否可以保证是该标准
I'm wondering if there are any circumstances where code like this will be incorrect due to floating point inaccuracies:
#include <math.h>
// other code ...
float f = /* random but not NAN or INF */;
int i = (int)floorf(f);
// OR
int i = (int)ceilf(f);
Are there any guarantees about these values? If I have a well-formed f
(not NAN or INF) will i
always be the integer that it rounds to, whichever way that is.
I can image a situation where (with a bad spec/implementation) the value you get is the value just below the true value rather than just above/equal but is actually closer. Then when you truncate it actually rounds down to the next lower value.
It doesn't seem possible to me given that integers can be exact values in ieee754 floating point but I don't know if float
is guaranteed to be that standard
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
C标准在指定浮点行为方面是草率的,因此从技术上讲,
floff(f)
可以产生f
或该ceilf的正确地板(f)
产生f
的正确上限。尽管如此,我知道没有C的实施方法是错误的。
如果是
floorf(一些变量)
,您有floorf( somenders ))
,有C实现这可能会以不同的方式评估表达,而不会获得相同的结果,就像贯穿了IEEE-754算术一样。如果C实现定义
__ stdc_iec_559 __
,则应使用IEEE-754算术评估表达式。尽管如此,
int i =(int)floorf(f);
当然不能保证将i
设置为f
的地板f
的范围不超出int
的范围。The C standard is sloppy in specifying floating-point behavior, so it is technically not completely specified that
floorf(f)
produces the correct floor off
or thatceilf(f)
produces the correct ceiling off
.Nonetheless, no C implementations I am aware of get this wrong.
If, instead of
floorf(some variable)
, you havefloorf(some expression)
, there are C implementations that may evaluate the expression in diverse ways that will not get the same result as if IEEE-754 arithmetic were used throughout.If the C implementation defines
__STDC_IEC_559__
, it should evaluate the expressions using IEEE-754 arithmetic.Nonetheless,
int i = (int)floorf(f);
is of course not guaranteed to seti
to the floor off
if the floor off
is out of range ofint
.