python - 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 作为输出。
任何建议如何获得更精确/准确的结果?
解决方案
您在 python 文档中有此效果的定义:
https://docs.python.org/2/tutorial/floatingpoint.html
您可以在打印时将结果格式化为您想要的 3 位数字:
print("%.3f" % np.float64(100) - np.float64(123.123))
推荐阅读
- python - Python 脚本突然无法在 PowerBI 服务上运行
- c# - Textbox.Text 重新排列字符串内容
- php - 将接口传递给另一个接口方法
- sql - 检查元组是否在每个子查询结果中(Oracle SQL)
- angular - 如何使用 ngFor Angular 动态创建许多模式?
- python - 如何在 IDE 编辑器 PyCharm 中运行 abaqus python 脚本
- c# - 起订量持久函数 IDurableOrchestrationContext 时设置 CallActivityAsync 始终返回 null
- javascript - Invariant Violation:对象作为 React 子对象无效(在 json 中使用 react-native 对象)
- java - 消除非显着排列
- bots - discordjs 只从特定频道读取消息