浮点小数精度

Float Fractional Precision

本文关键字:精度 小数      更新时间:2023-10-16

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

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

std::numeric_limits<float>::digits10

发件人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。这些舍入误差在表示中不能超过一位,数字10计算为(24-1)*std::log10(2),即6.92。向下舍入得到值6。

第2版:这表明,对于任何浮点,数字不是7,而是只有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。

如果我正确理解你的问题,答案是6。

#include <iostream>
#include <string>
#include <sstream>
#include <iomanip>
using namespace std;
int main() {
    int i = 10;  /* Number of distinct number after 1 place of decimal */
    int k = 1;   /* Number of decimal places */
    for(;/* ever */;)
    {
        float prev = 0.0f;
        for(int j = 1; j <= i; ++j)
        {
            stringstream ss;
            ss << "0.";  /* Prepare stream with 0. followed by k digit number with leading zeroes */
            ss << setfill('0') << setw(k) << j;
            float next; /* Read the number */
            ss >> next;
            if(prev == next) return 0;  /* If previous number and current number can not be distinguished */
            prev = next;
        }
        cout << "Works for " << k << " places" << endl;
        i *= 10; /* 10 times more tests to be conducted for 1 more decimal places */
        k++;     /* Try for more decimal places */
    }
    return 0;
}

代码的作用

1.将精度设置为小数后1位2.将0.0与0.1、0.1与0.2进行比较……将0.8与0.9和0.9进行比较对于1.0,如果其中任何一个相等(不区分),则退出。否则打印作品1处。3.将精度设置为小数后2位4.比较0.00与0.01、0.01与0.02…0.98与0.99和0.99使用1.00,如果其中任何一个相等(不区分),则退出。否则印刷作品2处。5.对3位及以上的数字重复类似的步骤,除非退出