Python Forum
Strange/odd outcome in decimals
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Strange/odd outcome in decimals
#1
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?
- Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid. Albert Einstein
Reply
#2
(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
Reply
#3
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
- Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid. Albert Einstein
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020