Fix float precision with decimal numbers

蓝咒 提交于 2020-02-15 12:36:12

问题


a = 1

for x in range(5):
    a += 0.1
    print(a)

This is the result:

1.1
1.2000000000000002
1.3000000000000003
1.4000000000000004
1.5000000000000004

How can I fix this? Is the round() function the only way? Can I set the precision of a variable before setting its value?


回答1:


can i set the precision of a variable before setting the value?

Use the decimal module which, unlike float(), offers arbitrary precision and can represent decimal numbers exactly:

>>> 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



回答2:


You could format your output like this;

a=1
for x in range(5):
    a += 0.1
    print("{:.9f}".format(a) )



回答3:


Assuming that your problem is only displaying the number, @Jaco 's answer does the job. However if you're concern about using that variable and potentially make comparisons or assigning to dictionary keys, I'd say you have to stick to round(). For example this wouldn't work:

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

You'd have to do:

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



回答4:


Formatted output has been duly suggested by @Jaco. However, if you want control of precision in your variable beyond pure output, you might want to look at the decimal module.

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


来源:https://stackoverflow.com/questions/35805512/fix-float-precision-with-decimal-numbers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!