gpt4 book ai didi

c++ - float 精度

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:10:09 30 4
gpt4 key购买 nike

float1.0f0.0f 之间有多少位精度,这样每个值都可以唯一表示?

例如,如果第一个小数 float 不能表示 0.13f,答案就是 float 只有一位精度。

最佳答案

std::numeric_limits<float>::digits10

来自 http://en.cppreference.com/w/cpp/types/numeric_limits/digits10

The standard 32-bit IEEE 754 floating-point type has a 24 bit fractional part (23 bits written, one implied), which may suggest that it can represent 7 digit decimals (24 * std::log10(2) is 7.22), but relative rounding errors are non-uniform and some floating-point values with 7 decimal digits do not survive conversion to 32-bit float and back: the smallest positive example is 8.589973e9, which becomes 8.589974e9 after the roundtrip. These rounding errors cannot exceed one bit in the representation, and digits10 is calculated as (24-1)*std::log10(2), which is 6.92. Rounding down results in the value 6.

编辑2:这表明该数字不是 7,而是任何 float 的 6 位数字,就像 std::numeric_limits<float>::digits10 一样电话会告诉你。

float orgF = 8.589973e9;
int i = orgF;
float f = i;
assert(f == orgF);

失败,因为往返更改了值。

因此,如果我们只寻找 1.0 和 0.0 之间的数字,肯定的答案是 7,因为有问题的最小正数是 8.589973e9。

关于c++ - float 精度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25785968/

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