如何处理浮点溢出? [英] How to handle a float overflow?

查看:272
本文介绍了如何处理浮点溢出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果一个值发生浮动溢出,我想将其设置为零,像这样...

If a float overflow occurs on a value, I want to set it to zero, like this...

m_speed += val;
if ( m_speed > numeric_limits<float>::max()) { // This might not even work, since some impls will wraparound after previous line
  m_speed = 0.f
}

但一旦 val code> m_speed ,溢出已经发生了(我假设如果我做了 if((m_speed + val)>)会发生同样的问题。 。)

but once val has been added to m_speed, the overflow has already occurred (and I'm assuming that the same problem would occur if i did if (( m_speed + val ) > ..).

如何检查以确保溢出将发生,而不会导致溢出?

How can I check to make sure an overflow is going to occur, without causing an overflow?

推荐答案

您可以:

if (numeric_limits<float>::max() - val < m_speed)
{
    m_speed = 0;
}
else
{
    m_speed += val;
}

另一种方法可能是:

m_speed += val;
if (m_speed == numeric_limits<float>::infinity())
    m_speed = 0;

但是请记住,当溢出实际发生时,结果是未定义的行为。所以虽然这可能适用于大多数机器,但不能保证。

But do keep in mind when an overflow actually occurs, the result is undefined behavior. So while this probably works on most machines, it isn't guaranteed. You're better of catching it before it happens.

因为这首先读不太容易, d将它包装到一个函数中:

Because this isn't trivial to read at first, I'd wrap it into a function:

template <typename T>
bool will_overflow(const T& pX, const T& pValue, 
                    const T& pMax = std::numeric_limits<T>::max())
{
    return pMax - pValue < pX;
}

template <typename T>
bool will_underflow(const T& pX, const T& pValue, 
                    const T& pMin = std::numeric_limits<T>::min())
{
    return pMin + pValue > pX;
}

m_speed = will_overflow(m_speed, val) ? 0 : m_speed + val;

这篇关于如何处理浮点溢出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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