首页 > 解决方案 > Python 3 中的计算精度

问题描述

在 Python 中,我得到了一个简单计算的意外结果:

100 - 123.123

返回:
-23.123000000000005

我期望 -23.123 作为输出。

所以我尝试了:

import numpy as np
np.float64(100) - np.float64(123.123)

返回:
-23.123000000000005

我期望 -23.123 作为输出。

任何建议如何获得更精确/准确的结果?

标签: pythonnumpyprecision

解决方案


您在 python 文档中有此效果的定义:

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

您可以在打印时将结果格式化为您想要的 3 位数字:

print("%.3f" % np.float64(100) - np.float64(123.123))

推荐阅读