Python 浮点精度
Python float point precision
我对python中的浮点精度问题感到困惑。
例如:
48.91 乘以 10000:
> 48.91 * 10000
489099.9999999999994
我输了精度,但如果我直接输入48.91作为float,它可以完美地表示它。
> 48.91
48.91
> float(48.91)
48.91
那为什么有时能保持精度有时不能??这种情况怎么处理??
阅读这些文章
https://docs.python.org/3/tutorial/floatingpoint.html
https://blog.tecladocode.com/decimal-vs-float-in-python/
TLDR;
尝试使用小数来处理这种情况
from decimal import Decimal
num = Decimal('48.91')
print(num * 10000)
我对python中的浮点精度问题感到困惑。
例如: 48.91 乘以 10000:
> 48.91 * 10000
489099.9999999999994
我输了精度,但如果我直接输入48.91作为float,它可以完美地表示它。
> 48.91
48.91
> float(48.91)
48.91
那为什么有时能保持精度有时不能??这种情况怎么处理??
阅读这些文章
https://docs.python.org/3/tutorial/floatingpoint.html
https://blog.tecladocode.com/decimal-vs-float-in-python/
TLDR;
尝试使用小数来处理这种情况
from decimal import Decimal
num = Decimal('48.91')
print(num * 10000)