C++ 何时会:标准::abs(x-y)<;标准::数值限制<;双重>;::min()
其中,有一个函数用于检查两个浮点值的相等性:C++ 何时会:标准::abs(x-y)<;标准::数值限制<;双重>;::min(),c++,C++,其中,有一个函数用于检查两个浮点值的相等性: 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
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();
}
模板
typename std::enable_if::is_integer,bool>::type
几乎相等(tx,ty,int-ulp)
{
//机器ε必须按所用值的大小进行缩放
//并乘以以ULPs为单位的所需精度(最后一位的单位)
return std::abs(x-y)std::numeric_limits::min()
返回可以表示的最小“正常”浮点值。IEEE754可以将介于0和std::numeric_limits::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());
}
//示例程序
#包括
#包括
#包括
int main()
{
标准::cout
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