如何在不引发异常的情况下进行通用除法
我想对任何类型 T 进行安全除法,我不想引发 CPU/FPU 异常,例如,如果浮点数除以零,它应该返回无穷大 (+/-INF)。
我应该编写自己的函数吗?或者有我可以使用的标准 C++ 函数吗?
如果我需要编写自己的函数,这个函数合适吗?
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();
}
}
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 standard 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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果浮点数除以零,从数学上来说,它是未定义的,而不是无穷大。原因就是极限法则。当你除以一个越来越小的大于零的数时,你倾向于接近正无穷大,当你除以越来越小的负数时,你倾向于接近负无穷大......在数轴上,它们是相反的,你不能将一件事定义为这两个对立面。因此,函数 1/x 在 0 处未定义。返回负无穷大或正无穷大都是不正确的。
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.