c++ - C++ 中的最小浮点正值

标签 c++ precision

在 C++ 中,乘法逆仍为有限的最小正值是多少? 试过numeric_limits<double>::epsilon()但事实并非如此 - 我得到的正值小于很多值。

#include <limits>//is it here?
void tfuuuuu()
{

   double d_eps,invd_eps;
   float f_eps,invf_eps;
   invd_eps = 1.0/d_eps;//invd_eps should be finite
   invf_eps = 1.f/f_eps;//invf_eps should be finite

}

最佳答案

我怀疑是否存在用于查找所需数字的标准库函数,但是,使用简单的二分查找查找所需值并不难:

#include <iostream>
#include <cmath>
#include <typeinfo>

template<typename T> T find_magic_epsilon(T from, T to) {
    if (to == std::nextafter(from, to)) return to;
    T mid = (from + to)/2;
    if (std::isinf((T)1.0/mid)) return find_magic_epsilon<T>(mid, to);
    else return find_magic_epsilon<T>(from, mid);
}

template<typename T> T meps() {
    return find_magic_epsilon<T>(0.0, 0.1);
}

template<typename T> T test_meps() {
    T value = meps<T>();
    std::cout << typeid(T).name() << ": MEPS=" << value
              << " 1/MEPS=" << (T)1.0/value << " 1/(MEPS--)="
              << (T)1.0/std::nextafter(value,(T)0.0) << std::endl;
}

int main() {
    test_meps<float>();
    test_meps<double>();
    test_meps<long double>();
    return 0;
}

上面脚本的输出:

f: MEPS=2.93874e-39 1/MEPS=3.40282e+38 1/(MEPS--)=inf
d: MEPS=5.56268e-309 1/MEPS=1.79769e+308 1/(MEPS--)=inf
e: MEPS=8.40526e-4933 1/MEPS=1.18973e+4932 1/(MEPS--)=inf

关于c++ - C++ 中的最小浮点正值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53462009/

相关文章:

c++ - 将临时 unique_ptr 传递给 VS2010 中的构造函数

c++ -/usr/bin/ld : cannot find

c++ - 学习按位编程的资源?

c - c中整数到 float 的隐式转换

c++ - 实际长 double 与 std::numeric_limits 不一致

java - 如何避免 Java 中 double 造成的精度损失?

c++ - 如何创建具有迭代器值的映射?

c++ - 如何访问私有(private)变量?

python - Pandas 数据框。更改 float 格式。保留类型 "float"

math - float 学有问题吗?