如何比较浮点数或双精度
How to compare float or double?
是否有内置库可以比较float或double
我不认为比较a == b
或a !=b
有任何意义。任何建议吗?
比较浮点数或双精度数的技术是使用fabs
bool isEqual(const float a,const float b)
{
return fabs(a - b) < std::numeric_limits<float>::epsilon();
}
对于std::numeric_limits
您可以简单地使用:
fabs(a-b) < eps // eps is the precision you want to achieve
我使用这个函数:
template <typename T>
bool approx(const T& x, const T& y, const T& eps = 1.0e-10)
{
if(x == y)
return true;
if(x == 0.0)
return (y < 0.0 ? -y : y) < eps;
if(y == 0.0)
return (x < 0.0 ? -x : x) < eps;
return (x < y ? y - x : x - y) < eps * ((x < 0.0 ? -x : x) + (y < 0.0 ? -y : y)) / 2.0;
}
相关文章:
- 在C++中序列化浮点数/双精度,编译为 WebAssembly
- 如何提高计算浮点数的精度?
- 我们如何清楚地知道 C/C++ 中的双精度或浮点数的精度?
- 这是为浮点数/双精度函数泛型的正确方法吗?
- 关于在C/C++中比较整数和浮点/双精度
- 如何在没有浮点数/双精度数的情况下生成均匀和高斯分布的伪随机数
- 具有 IEEE 754 浮点双精度数据类型的安全往返整数值
- 将浮点浮点/双精度的其余部分转换为整数
- 为什么在C和C++中没有浮点/双精度的除法余数运算
- 使用浮点/双精度作为循环变量
- 字符数据浮点数/双精度数
- 宏或函数,用于根据给定的符号、尾数和指数构造浮点(双精度)
- C++将SATOSHI(uint64_t)转换为不带浮点/双精度的BTC(string)
- C++将字符串转换为浮点/双精度,而不会丢失数据
- 将输入字符串转换为浮点/双精度C++
- 在运行时定义双精度或浮点数的精度/大小
- 整数和分数为浮点数/双精度
- 在c++中控制浮点数的精度
- c++中浮点数/双精度数的比较
- 以 32 个十进制数字分析浮点数/双精度