我试图找到可以存储在单个精度浮点数中的最小(正)值(最接近零)。使用
<limits>
标头我可以获得该值,但如果我将其设置得小得多,则浮点数仍然可以容纳它并给出正确的结果。这是一个测试程序,用 g++ 5.3.0 编译。
#include <limits>
#include <iostream>
#include <math.h>
using namespace std;
int main()
{
float a = numeric_limits<float>::max();
float b = numeric_limits<float>::min();
a = a*2;
b = b/pow(2,23);
cout << a << endl;
cout << b << endl;
}
正如我所料,“a”给出无穷大,但“b”即使在将最小值除以 2^23 之后仍然保持良好的结果,之后它给出 0。
给出
numeric_limits<float>::min()
的值是 2^(-126),我相信这是正确的答案,但为什么我的程序上的浮点数持有这么小的数字?
std::numeric_limits::min
给出可以在不损失精度的情况下表示的最小非零值。 std::numeric_limits::lowest
给出最小的可表示值。对于 IEEE 表示,这是一个 subnormal 值(以前称为非标准化)。
来自维基百科https://en.wikipedia.org/wiki/Single- precision_floating-point_format:
最小正正常值为 2^−126 ≈ 1.18 × 10^−38 并且 最小正(非正规)值为 2^−149 ≈ 1.4 × 10^−45。
所以,对于
cout << (float)pow(2,-149)
<< "-->" << (float)pow(2,-150)
<< "-->" << (float)pow(2,-151) << endl;
我得到:
1.4013e-45-->0-->0
我正在尝试找到我能找到的最小值(最接近零) 存储在单个精度浮点数中
0 是可以存储在任何精度浮点数中的最接近 0 的值。事实上,你可以用两种方式存储它,因为有正0和负0。
编辑:我编辑了问题以指定肯定,但这是最初提出的问题的正确答案。