Python Forum
Strange/odd outcome in decimals - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: General (https://python-forum.io/forum-1.html)
+--- Forum: News and Discussions (https://python-forum.io/forum-31.html)
+--- Thread: Strange/odd outcome in decimals (/thread-35895.html)



Strange/odd outcome in decimals - Jeff900 - Dec-27-2021

A few weeks ago I wanted to simply print the outcome of some calculations, just as a reference at that moment. But ever since I am still wondering why some of the results has 16 decimals with the last result not exactly 0. It was a calculation as below, but it happens with other decimals too: not only 0.4.

for item in range(10):
    print(item * 0.4)
Output:
0.0 0.4 0.8 1.2000000000000002 1.6 2.0 2.4000000000000004 2.8000000000000003 3.2 3.6
It might be explainable, maybe even mathematical, but I still can't figure out why this happens. Someone has an idea?


RE: Strange/odd outcome in decimals - snippsat - Dec-27-2021

(Dec-27-2021, 10:30 AM)Jeff900 Wrote: It might be explainable, maybe even mathematical, but I still can't figure out why this happens. Someone has an idea?
Basic answer about Floating-Point arithmetic.
Floating Point Arithmetic: Issues and Limitations

In most cases it doesn't matter as it close enough,
there is decimal that can help eg if doing financial calculation where this can matter.
from decimal import Decimal

pennies = input('Enter pennies: ')
dollars = Decimal(pennies) * Decimal('.01')
print(f'{pennies} pennies are worth ${dollars} in dollars')
Output:
Enter pennies: 35 35 pennies are worth $0.35 in dollars
from decimal import Decimal

for item in range(10):
    print(Decimal(item) * Decimal('0.4'))
Output:
0.0 0.4 0.8 1.2 1.6 2.0 2.4 2.8 3.2 3.6



RE: Strange/odd outcome in decimals - Jeff900 - Dec-27-2021

Quote:In most cases it doesn't matter as it close enough

Yes, in my case too and probably it has never been an issue anyway in my projects. Still good to know, thank you for sharing the links, that clears things up! Smile