用十进制数修复浮点精度
Fix float precision with decimal numbers
a = 1
for x in range(5):
a += 0.1
print(a)
这是结果:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
我该如何解决这个问题? round()
函数是唯一的方法吗?我可以在设置变量值之前设置变量的精度吗?
您可以像这样格式化您的输出;
a=1
for x in range(5):
a += 0.1
print("{:.9f}".format(a) )
can i set the precision of a variable before setting the value?
使用 decimal
module which, unlike float()
,提供任意精度并可以精确表示十进制数:
>>> from decimal import Decimal, getcontext
>>>
>>> getcontext().prec = 5
>>>
>>> a = Decimal(1)
>>>
>>> for x in range(5):
... a += Decimal(0.1)
... print(a)
...
1.1000
1.2000
1.3000
1.4000
1.5000
假设您的问题只是显示数字,@Jaco 的回答就可以了。但是,如果您担心使用该变量并可能进行比较或分配给字典键,我会说您必须坚持使用 round()。例如,这是行不通的:
a = 1
for x in range(5):
a += 0.1
print('%.1f' % a)
if a == 1.3:
break
1.1
1.2
1.3
1.4
1.5
你必须做的:
a = 1
for x in range(5):
a += 0.1
print('%.1f' % a)
if round(a, 1) == 1.3:
break
1.1
1.2
1.3
@Jaco 已适当建议格式化输出。但是,如果您希望控制变量的精度超出纯输出,您可能需要查看 decimal
模块。
from decimal import Decimal
a = 1
for x in range(3):
a += Decimal('0.10') # use string, not float as argument
# a += Decimal('0.1000')
print(a) # a is now a Decimal, not a float
> 1.10 # 1.1000
> 1.20 # 1.2000
> 1.30 # 1.3000
a = 1
for x in range(5):
a += 0.1
print(a)
这是结果:
1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004
我该如何解决这个问题? round()
函数是唯一的方法吗?我可以在设置变量值之前设置变量的精度吗?
您可以像这样格式化您的输出;
a=1
for x in range(5):
a += 0.1
print("{:.9f}".format(a) )
can i set the precision of a variable before setting the value?
使用 decimal
module which, unlike float()
,提供任意精度并可以精确表示十进制数:
>>> from decimal import Decimal, getcontext
>>>
>>> getcontext().prec = 5
>>>
>>> a = Decimal(1)
>>>
>>> for x in range(5):
... a += Decimal(0.1)
... print(a)
...
1.1000
1.2000
1.3000
1.4000
1.5000
假设您的问题只是显示数字,@Jaco 的回答就可以了。但是,如果您担心使用该变量并可能进行比较或分配给字典键,我会说您必须坚持使用 round()。例如,这是行不通的:
a = 1
for x in range(5):
a += 0.1
print('%.1f' % a)
if a == 1.3:
break
1.1
1.2
1.3
1.4
1.5
你必须做的:
a = 1
for x in range(5):
a += 0.1
print('%.1f' % a)
if round(a, 1) == 1.3:
break
1.1
1.2
1.3
@Jaco 已适当建议格式化输出。但是,如果您希望控制变量的精度超出纯输出,您可能需要查看 decimal
模块。
from decimal import Decimal
a = 1
for x in range(3):
a += Decimal('0.10') # use string, not float as argument
# a += Decimal('0.1000')
print(a) # a is now a Decimal, not a float
> 1.10 # 1.1000
> 1.20 # 1.2000
> 1.30 # 1.3000