gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-31 00:26:12 25 4
gpt4 key购买 nike

在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com