c++ - 何时:std::abs(x -y) < std::numeric_limits::分钟()
问题描述
在这个链接中,有一个函数可以检查 2 个浮点值是否相等:
template<class T>
typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type
almost_equal(T x, T y, int ulp)
{
// the machine epsilon has to be scaled to the magnitude of the values used
// and multiplied by the desired precision in ULPs (units in the last place)
return std::abs(x-y) <= std::numeric_limits<T>::epsilon() * std::abs(x+y) * ulp
// unless the result is subnormal
|| std::abs(x-y) < std::numeric_limits<T>::min();
}
但我不太明白什么时候会std::abs(x-y) < std::numeric_limits<T>::min()
真正发生?有什么例子吗?谢谢。
解决方案
std::numeric_limits<T>::min()
返回可以表示的最小“正常”浮点值。IEEE754 可以将 0 和之间的值表示std::numeric_limits<T>::min()
为“次正常”数字。看看这个问题,它有几个解释这个问题的答案。
您可以轻松地生成次正常值:
// Example program
#include <iostream>
#include <limits>
#include <cmath>
int main()
{
std::cout << "double min: " << std::numeric_limits<double>::min() << " subnormal min: ";
std::cout << std::numeric_limits<double>::denorm_min() << '\n';
double superSmall = std::numeric_limits<double>::min();
std::cout << std::boolalpha << "superSmall is normal: " << std::isnormal(superSmall) << '\n';
double evenSmaller = superSmall/2.0;
std::cout << "evenSmaller = " << evenSmaller << '\n';
std::cout << std::boolalpha << "evenSmaller is normal: " << std::isnormal(evenSmaller);
std::cout << std::boolalpha << "std::abs(superSmall - evenSmaller) < std::numeric_limits<double>::min(): " << (std::abs(superSmall - evenSmaller) < std::numeric_limits<double>::min());
}
在我的机器上生成以下内容:
double min: 2.22507e-308 subnormal min: 4.94066e-324
superSmall is normal: true
evenSmaller = 1.11254e-308
evenSmaller is normal: false
std::abs(superSmall - evenSmaller) < std::numeric_limits<double>::min(): true
推荐阅读
- python-3.x - 如何在远程进程之间使用 Python3.9.2 multiprocessing.SyncManager?
- discord - 所以不和谐机器人状态.....我该如何设置它们?
- wordpress - 登录到 Wordpress Elementor 的外部站点
- java - 最大可能的数组需要多少内存?
- express - 如何控制台注销我从特快专递请求中返回的内容
- html - nav ul 中的 Href 没有响应
- postman - Autotask RestApi 字段定义
- c - 如何将整数转换为字符串(函数)?
- typescript - 接受带参数函数的函数,返回具有相同参数但不允许参数的函数
- javascript - 在没有 CSS 类的 react-bootstrap 中覆盖下拉切换的内联样式