接近于零的浮点值可能会导致一个除以零错误? [英] Can a near-zero floating value cause a divide-by-zero error?

查看:159
本文介绍了接近于零的浮点值可能会导致一个除以零错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家都知道,你不应该直接比较花车,而是用宽容:

Everybody knows you're not supposed to compare floats directly, but rather using a tolerance:

float a,b;
float epsilon = 1e-6f;
bool equal = (fabs(a-b) < epsilon);

我不知道是否同样适用于在师使用它之前比较值为零。

I was wondering if the same applies to comparing a value to zero before using it in division.

float a, b;
if (a != 0.0f) b = 1/a; // oops?

难道我还需要在这种情况下有小量的比较?

Do I also need to compare with epsilon in this case?

推荐答案

被零浮点除法是不是一个错误。它提出了一个浮点异常(这是一个空操作,除非你正在积极检查他们)在支持浮点异常实现,并有明确界定的结果:或正或负无穷大(如果分子不为零),或南(如果分子是零)。

Floating point division by zero is not an error. It raises a floating point exception (which is a no-op unless you're actively checking them) on implementations that support floating point exceptions, and has well-defined result: either positive or negative infinity (if the numerator is nonzero), or NAN (if the numerator is zero).

也有可能获得无穷大(和一个溢出异常)作为结果,当分母不为零,但非常接近于零(例如低于正常),但再次,这不是一个错误。这一点是多么浮工作。

It's also possible to get infinity (and an overflow exception) as the result when the denominator is nonzero but very close to zero (e.g. subnormal), but again this is not an error. It's just how floating point works.

编辑:需要注意的是,埃里克在评论中指出的那样,这个答案假定附件F,C标准,详细的浮点行为,并与IEEE对准它的可选部分的要求标准浮点。在没有IEEE算法,C并没有定义被零浮点除法(而事实上,所有的浮点运算的结果是实现定义的,可以定义为完全是一派胡言,仍然符合C标准),所以如果你正在处理一个古怪的C语言实现,不兑现IEEE浮点,你必须请查询您正使用来回答这个问题的实施文档。

Note that, as Eric has pointed out in the comments, this answer assumes the requirements of Annex F, an optional part of the C standard detailing floating point behavior and aligning it with the IEEE standard for floating point. In the absence of IEEE arithmetic, C does not define floating point division by zero (and in fact, the results of all floating point operations are implementation-defined and may be defined as complete nonsense and still conform to the C standard), so if you're dealing with an outlandish C implementation that does not honor IEEE floating point, you'll have to consult the documentation for the implementation you're using to answer this question.

这篇关于接近于零的浮点值可能会导致一个除以零错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆