Precision and Error

This document should show you that there is some error involved, when working with floating point numbers.


In [7]:
for i in range(1, 30):
    print(1 + 10 ** -i)


1.1
1.01
1.001
1.0001
1.00001
1.000001
1.0000001
1.00000001
1.000000001
1.0000000001
1.00000000001
1.000000000001
1.0000000000001
1.00000000000001
1.000000000000001
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0
1.0

Use the decimal module if you need high precision


In [13]:
from decimal import *
getcontext().prec = 27

In [14]:
for i in range(1, 30):
    print(Decimal(1) + Decimal(10) ** -i)


1.1
1.01
1.001
1.0001
1.00001
1.000001
1.0000001
1.00000001
1.000000001
1.0000000001
1.00000000001
1.000000000001
1.0000000000001
1.00000000000001
1.000000000000001
1.0000000000000001
1.00000000000000001
1.000000000000000001
1.0000000000000000001
1.00000000000000000001
1.000000000000000000001
1.0000000000000000000001
1.00000000000000000000001
1.000000000000000000000001
1.0000000000000000000000001
1.00000000000000000000000001
1.00000000000000000000000000
1.00000000000000000000000000
1.00000000000000000000000000