开发者

how to do generic division without raising exception

开发者 https://www.devze.com 2023-04-09 11:55 出处:网络
I want to do safe division for any type T, which I don\'t want to raise CPU/FPU exception, for example if a float is divided by zero it should return infinity (+/-INF).

I want to do safe division for any type T, which I don't want to raise CPU/FPU exception, for example if a float is divided by zero it should return infinity (+/-INF).

Should I write my own function? or is there any standar开发者_StackOverflow社区d C++ function that I can use?

if I need to write my own function, does this function is right?

template<typename T> bool isSameSign(const T& a, const T& b)
{       
    return ((((a)<0)==((b)<0))&&(((a)>0)==((b)>0)));
}

template<typename T> T safeDiv (const T& lhs, const T& rhs)
{
    if(std::abs(rhs) > std::numeric_limits<T>::epsilon)
    {
        if(std::abs(lhs) > std::numeric_limits<T>::epsilon)
        {
            return lhs/rhs;
        }
        else
        {
            return std::numeric_limits<T>::quiet_NaN();
        }
    }
    else if(isSameSign<T>(lhs,rhs))
    {
        return std::numeric_limits<T>::infinity();
    }
    else
    {
        return -std::numeric_limits<T>::infinity();
    }
}


If a float is divided by zero, mathematically speaking, it is undefined, not infinity. The reason is the law of limits. As you divide by a smaller and smaller number greater than zero, you tend to approach positive infinity, and as you divide by a smaller and smaller negative number you tend toward negative infinity.... On a number line those are opposites, and you can't define one thing as both of those opposites. The function 1/x is therefore undefined at 0. Returning negative or positive infinity would be incorrect.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号