C ++中最小的浮点正值 [英] Smallest floating point positive values in C++

查看:88
本文介绍了C ++中最小的浮点正值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,它们的乘法逆仍然是有限的,最小的正值是多少? 尝试过numeric_limits<double>::epsilon(),但不是-小于 的正值会得到正值.

What are the smallest positive values in C++ for which their multiplicative inverse will still be finite? Have tried numeric_limits<double>::epsilon() but it isn't it - am getting positive values for much smaller values than that.

#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

}

推荐答案

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

I doubt there is a standard library function for finding the number you need, however, it is not too hard to find the needed value using a simple binary search:

#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 ++中最小的浮点正值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆