Python中的小数模块不准确
from decimal import *
Pi=Decimal(3.141592653589793238462643383279502884197169399373)
print(Pi)
实际输出:
3.141592653589793115997963468544185161590576171875
输出应该是:
3.141592653589793238462643383279502884197169399373
为什么值会改变?
from decimal import *
Pi=Decimal(3.141592653589793238462643383279502884197169399373)
print(Pi)
Actual output:
3.141592653589793115997963468544185161590576171875
Output should be:
3.141592653589793238462643383279502884197169399373
Why does the value change?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在访问a floating-point number ,and 浮点数本质上是不正确的(另请参阅 python手册)。
要将精确编号传递给小数构造函数,请以字符串的形式传递。
如果您有浮点变量,则可以先将其施加到字符串,然后将其施加到十进制中,以避免一些 floating-probation-point dormision:
如果您需要完整的精度,只需一路处理小数:
You're passing in a floating-point number to the Decimal constructor, and floating-point numbers are inherently imprecise (see also the Python manual).
To pass in a precise number to the Decimal constructor, pass it in as a string.
If you have a floating-point variable, you can cast it to a string first, then to a Decimal to avoid some floating-point imprecision:
If you need full precision, just work with Decimals all the way:
您应该将字符串传递给 Decimal(),而不是浮点数,浮点数一开始就是不精确的。另外,请注意 Python 文档中的以下内容
You should pass a string to
Decimal()
, not a float, floats are imprecise to begin with. Also, note the following from the Python docs