c++ - base10 和浮点表示

标签 c++ floating-point

<分区>

base10 中的 0.1 在 double 表示中没有对应。

在 C++ 中是否有任何保证,即没有小数部分且位数减去或等于 std::numeric_limits::digit10 的 base10 数字必须具有正确/准确的 double 表示?

最佳答案

根据 Dietmar Kühl’s answer , C++ 标准中的语句暗示 [0, rd) 中的整数可以精确表示,其中 rstd::numeric_limits<type>::radix dstd::numeric_limits<type>::digits .

这反过来似乎暗示一个不超过 std::numeric_limits<type>::digits10 的整数可以精确表示 base-10 数字。


旁白:C++ 标准对 std::numeric_limits<type>::digits10 的定义存在一些问题.

标准说这是“可以不改变地表示的以 10 为基数的数字的数量”。这应该只是简单的以 10 为基数的数字,即整数,还是关于整个格式范围内精度的声明?一个非规范的脚注说这等同于 C 标准定义的 FLT_DIG、DBL_DIG 和 LDBL_DIG。 C 标准在一条语句中给出了两个定义:

number of decimal digits, q, such that any floating-point number with q decimal digits can be rounded into a floating-point number with p radix b digits and back again without change to the q decimal digits,

和:

p log10 b if b is a power of 10
floor((p-1) log10 b) otherwise

我不认为前者是一个好的定义。后者为 IEEE-754 32 位二进制 float 提供了 7,但 1.5e-45 是一个具有 2 个十进制数字的 float ,并将其四舍五入为 IEEE-754 32 位二进制 float 并返回给1.401…e-45(因为它处于次正常区间)。因此,任何具有 7 位十进制数字的 float 都可以四舍五入为 float 并再次返回而不更改为 7 位十进制数字,这是不正确的。

关于c++ - base10 和浮点表示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21137678/

相关文章:

c++ - 将 auto_ptr 转换为 shared_ptr

c++ - 具有通用引用的过载解决方案

PHP: number_format 四舍五入

c++ - 使用具有 C++ 继承的 CMake 时,应该如何组织目录结构?

c++ - 在 Windows 上使用 Gtest 和 Gmock

javascript - IEEE 754 中 Infinity 的用例是什么

c - 递增 float 的有效位数

javascript - PHP floatval 奇异解析

c++ - 你不应该从 std::vector 继承

比较 C 中的 float