是否有标准的 C 方法来打印浮点值 "perfectly" a la Dragon4?
Is there a standard C way to print floating-point values "perfectly" a la Dragon4?
正在阅读 Here be dragons: advances in problems you didn’t even know you had 我注意到他们将新算法与 glibc printf
:
中使用的算法进行了比较
Grisu3 is about 5 times faster than the algorithm used by printf in GNU libc
但与此同时,我未能找到 printf
的任何格式说明符,它会自动找到要打印的最佳小数位数。我尝试过的所有设置都有一些奇怪的默认值,例如 %f
的小数点后 6 位或 %g
的小数点后 2 位或 %e
.
的小数点后 6 位
我如何实际使用文章中提到的 glibc 中的算法实现? glibc 中真的有这样的实现吗?标准是否以任何方式讨论过它?
没有"best number of decimal places"这样的东西,因为浮点数不存储为十进制数。因此,您需要定义 "best" 的含义。如果您想在不丢失任何信息的情况下打印数字,C11 会为您提供格式说明符 %a
(行为未指定的非标准化浮点数除外)。
C11 标准的默认值是 %f
和 %e
的 6 位数字,%g
的默认值为:
Let P equal the
precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero.
Then, if a conversion with style E would have an exponent of X:
— if P > X ≥ −4, the conversion is with style f (or F) and precision
P − (X + 1).
— otherwise, the conversion is with style e (or E) and precision P − 1.
如果您想使用该算法,请为其实现您自己的功能。或者希望 glibc 在过去 5 年中已经实现了它。或者只是重新考虑打印浮点数的性能是否真的是您遇到的问题。
This 是实际的文章。博客 post 指的是第 7 节中的结果(换句话说,“他们”没有比较博客 post 中的任何内容,“他们”正在反省实际文章中的信息,省略了关键详情):
Dragon4 或 Grisu3 的实现可以在现代编程语言的实现中找到,这些语言指定了这种“最小小数位数”方式(我建议您避免称其为“完美”)。 Java 在某些情况下使用这种类型的十进制转换,Ruby 也是如此。 C 不是指定“最小十进制数”转换为十进制的语言之一,因此编译器或 libc 没有理由为 Dragon4 或 Grisu3 提供实现。
正在阅读 Here be dragons: advances in problems you didn’t even know you had 我注意到他们将新算法与 glibc printf
:
Grisu3 is about 5 times faster than the algorithm used by printf in GNU libc
但与此同时,我未能找到 printf
的任何格式说明符,它会自动找到要打印的最佳小数位数。我尝试过的所有设置都有一些奇怪的默认值,例如 %f
的小数点后 6 位或 %g
的小数点后 2 位或 %e
.
我如何实际使用文章中提到的 glibc 中的算法实现? glibc 中真的有这样的实现吗?标准是否以任何方式讨论过它?
没有"best number of decimal places"这样的东西,因为浮点数不存储为十进制数。因此,您需要定义 "best" 的含义。如果您想在不丢失任何信息的情况下打印数字,C11 会为您提供格式说明符 %a
(行为未指定的非标准化浮点数除外)。
C11 标准的默认值是 %f
和 %e
的 6 位数字,%g
的默认值为:
Let P equal the precision if nonzero, 6 if the precision is omitted, or 1 if the precision is zero. Then, if a conversion with style E would have an exponent of X: — if P > X ≥ −4, the conversion is with style f (or F) and precision P − (X + 1). — otherwise, the conversion is with style e (or E) and precision P − 1.
如果您想使用该算法,请为其实现您自己的功能。或者希望 glibc 在过去 5 年中已经实现了它。或者只是重新考虑打印浮点数的性能是否真的是您遇到的问题。
This 是实际的文章。博客 post 指的是第 7 节中的结果(换句话说,“他们”没有比较博客 post 中的任何内容,“他们”正在反省实际文章中的信息,省略了关键详情):
Dragon4 或 Grisu3 的实现可以在现代编程语言的实现中找到,这些语言指定了这种“最小小数位数”方式(我建议您避免称其为“完美”)。 Java 在某些情况下使用这种类型的十进制转换,Ruby 也是如此。 C 不是指定“最小十进制数”转换为十进制的语言之一,因此编译器或 libc 没有理由为 Dragon4 或 Grisu3 提供实现。