【问题标题】:What is the precision of cpp_dec_float_50?cpp_dec_float_50 的精度是多少?
【发布时间】:2016-01-07 17:30:34
【问题描述】:

查看名称和 Boost Multiprecision documentation 我预计 cpp_dec_float_50 数据类型的精度为 50 位小数:

使用 typedef cpp_dec_float_50 隐藏了多精度的复杂性,允许我们定义具有 50 位精度的变量,就像内置的 double 一样。

(虽然我不明白与 double 的比较——我的意思是 double 通常实现二进制浮点运算,而不是十进制浮点运算。)

这也与以下代码的输出相匹配(除了双精度部分,但这是预期的):

cout << std::numeric_limits<boost::multiprecision::cpp_dec_float_50>::digits10
  << '\n';
// -> 50
cout << std::numeric_limits<double>::digits10 << '\n';
// -> 15

但是为什么下面的代码会打印 74 位呢?

#include <boost/multiprecision/cpp_dec_float.hpp>

// "12" repeated 50 times, decimal point after the 10th digit
boost::multiprecision::cpp_dec_float_50 d("1212121212.121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212121212");
cout << d.convert_to<string>() << '\n';
// Expected output: 50 digits
// Actual output: 74 digits
// -> 1212121212.1212121212121212121212121212121212121212121212121212121212121212

str() 成员函数按预期工作,例如

cout << d.str(50) << '\n';

只打印 50 位数字 - 其中it is documented as:

返回格式化为字符串的数字,至少包含精度数字,如果科学为真,则返回科学格式。

【问题讨论】:

    标签: c++ boost floating-point precision multiprecision


    【解决方案1】:

    您所看到的可能与内部使用的保护数字有关。原因是即使是十进制表示也具有有限的准确性(想想 ("100.0" / "3.0") * "3.0")。

    为了在计算过程中得到合理的舍入误差,存储的精度会大于保证的精度。

    总而言之:始终具体说明您的预期精度。在您的示例中,d.str(50) 可以。

    (在现实场景中,您应该希望跟踪输入的精度并推断输出的精度。大多数情况下,人们只是保留多余的精度,只打印他们感兴趣的部分) em>

    【讨论】:

    • 顺便说一句,您可以为该报价添加参考吗?
    • @maxschlepzig 我自己说的。应该是一个“侧边栏”的东西。我指出的逻辑是具有明确误差范围的科学测量。
    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 2010-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    相关资源
    最近更新 更多