浮动分数精度 [英] Float Fractional Precision

查看:142
本文介绍了浮动分数精度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

float 1.0f 之间有多少精度

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

解决方案

  std :: numeric_limits< float> :: digits10 

$ b b

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


标准的32位IEEE 754浮点类型有一个24位小数部分(写入的23位,一个暗示的),这可以暗示它可以表示7位小数(24 * std :: log10(2)是7.22),但是相对舍入误差是不均匀的并且一些浮点值7个十进制数不能转换为32位浮点和反转:最小的正例子是8.589973e9,在往返之后变为8.589974e9。这些舍入误差不能超过表示中的一个比特,并且digits10被计算为(24-1)* std :: log10(2),这是6.92。舍入结果为值6.


Edit2:
这表示该数​​字不是7,任何浮动,就像 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。


How many places of precision does a float have between 1.0f and 0.0f such that every value could be uniquely represented?

For example if the first fractional number float couldn't represent 0.13f the answer would be that a float only had 1 place of precision.

解决方案

std::numeric_limits<float>::digits10

From 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.

Edit2: This shows that the number is not 7 but only 6 digits for any float, just like the std::numeric_limits<float>::digits10 call will tell.

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

This will fail as the roundtrip changes the value.

So if we are only looking for numbers between 1.0 and 0.0, positive the answer is 7, as the lowest positive number which has a problem is 8.589973e9.

这篇关于浮动分数精度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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