Notice the below results in python interpreter.
>>> b=245.353
>>> print('%.50f'%b)
245.35300000000000864019966684281826019287109375000000
After the 14th decimal place, numbers other than zeros start appearing and they remain until 44th place.
Python documentation in Floating Point Arithmetic: Issues and Limitations mentions this limitation but the solutions mentioned in the documentation doesn't work for some cases as explained below.
To test how it affects the results of arithmetic operations with b, I tried some multiplications.
Multiplying 5.132435246464... with the value of b shown by python upto 50 decimal places.
>>> print('%.50f'%(5.132435246464363423432432432342432324342*245.35300000000000864019966684281826019287109375000000))
1259.25838502577107647084631025791168212890625000000000
Multiplying 5.132435246464... with b
>>> print('%.50f'%(5.132435246464363423432432432342432324342*b))
1259.25838502577107647084631025791168212890625000000000
Multiplying 5.132435246464... with 245.353
>>> print('%.50f'%(5.132435246464363423432432432342432324342*245.353))
1259.25838502577107647084631025791168212890625000000000
All the 3 results are exactly the same.
To check the true results, I wrote a program to multiply 2 numbers digit by digit as done on pen and paper to not loose accuracy. It is slow but accurate.
Now doing the same calculations with my program -
Multiplying 5.132435246464... with the value of b shown by python upto 50 decimal places
5.132435246464363423432432432342432324342 * 245.35300000000000864019966684281826019287109375000000
= 1259.25838502577100337468290116624347509546633362424989047667622799053788185119628906250000000
multiplying 5.132435246464... with 245.353
5.132435246464363423432432432342432324342 * 245.35300000000000000000000000000000000000000000000000
= 1259.25838502577095902941759457251279807428272600000000000000000000000000000000000000000000000
Both the results are different from each other as well as from the results of previous 3 operations.
The results start to differ at 14th decimal place.
The documentation suggests to use Decimal and Fraction libraries.
Fraction Library
>>> g = Fraction('245.353')
>>> g
Fraction(245353, 1000)
>>> print('%.50f'%g)
245.35300000000000864019966684281826019287109375000000
Being more explicit didn't help.
>>> g = Fraction('245.35300000000000000000000000000000000000000000')
>>> g
Fraction(245353, 1000)
>>> print('%.50f'%g)
245.35300000000000864019966684281826019287109375000000
Same thing happens with Decimal library
>>> d = Decimal('245.353')
>>> d
Decimal('245.353')
>>> print('%.50f'%d)
245.35300000000000864019966684281826019287109375000000
Being more explicit
>>> d = Decimal('245.353000000000000000000000000000000000')
>>> d
Decimal('245.353000000000000000000000000000000000')
>>> print('%.50f'%d)
245.35300000000000864019966684281826019287109375000000
This severely affects a applied numerical math program.
- How can 245.353000000000000 (more than 14 decimal places) be stored in python?