python - 打印 Python 和 C++ double 时的精度差异

标签 python c++ floating-point double

我现在对此感到惊叹:

C++ 11

#include <iostream>
#include <iomanip>
#include <limits>

int main()
{
  double d = 1.305195828773568;
  std::cout << std::setprecision(std::numeric_limits<double>::max_digits10) << d << std::endl;
  // Prints  1.3051958287735681
}

Python

>>> repr(1.305195828773568)
'1.305195828773568'

这是怎么回事,为什么 C++ 中多了个 1?

到目前为止,我认为 C++ 和 Python 在后台使用相同的 64 位 IEEE double;这两个格式化函数都应该打印完整的精度。

最佳答案

您也可以强制 python 打印 1(以及更多以下数字):

print('{:.16f}'.format(1.305195828773568))
# -> 1.3051958287735681

来自 https://docs.python.org/2/tutorial/floatingpoint.html :

>>> 7205759403792794 * 10**30 // 2**56
100000000000000005551115123125L

In versions prior to Python 2.7 and Python 3.1, Python rounded this value to 17 significant digits, giving ‘0.10000000000000001’. In current versions, Python displays a value based on the shortest decimal fraction that rounds correctly back to the true binary value, resulting simply in ‘0.1’.

“打印全精度”很难做到:什么是全精度? float 的表示是二进制的;只有 2 的幂的分数可以精确表示(完全精确);大多数小数部分不能以 2 为底精确表示。

但是内存中的 float 对于python和c++是一样的;只是字符串表示不同。

关于python - 打印 Python 和 C++ double 时的精度差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32386768/

相关文章:

python - 通过 cron 从 bash 脚本内部运行 python 文件

c++ - 如何在 C++ 中使用运算符 ^

c++ - 如何通过函数指针调用派生方法?

mysql - Perl DBI/MySQL - 不能用于特定的浮点值

在 C 的子例程中将 float 转换为字符串

python - imblearn smote+enn 采样了多数类

python - 升级到 django-rest-framework 3.5.3 后不允许使用 HEAD 方法

python - OpenCV 像人眼一样找到主观轮廓

c++ - 如何更新 boost::io::ios_all_saver?

c - printf double 输出不正确