Python Forum
why is there an unexpected maths result from a float calculation?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
why is there an unexpected maths result from a float calculation?
#1
One of my students asked why - entering 35 as the input gets a strange answer - see print dollars result. It is strange. The answer should just be 0.35

pennies = int(input('Enter pennies: '))
dollars = pennies * .01
print(f'{pennies} pennies are worth ${dollars:.2f} in dollars')
print(dollars)
Reply
#2
https://docs.python.org/3/faq/design.htm...inaccurate Wrote:Why are floating-point calculations so inaccurate?
Users are often surprised by results like this:

>>>
>>> 1.2 - 1.0
0.19999999999999996
and think it is a bug in Python. It’s not. This has little to do with Python, and much more to do with how the underlying platform handles floating-point numbers.

The float type in CPython uses a C double for storage. A float object’s value is stored in binary floating-point with a fixed precision (typically 53 bits) and Python uses C operations, which in turn rely on the hardware implementation in the processor, to perform floating-point operations. This means that as far as floating-point operations are concerned, Python behaves like many popular languages including C and Java.

Many numbers that can be written easily in decimal notation cannot be expressed exactly in binary floating-point. For example, after:

>>>
>>> x = 1.2
the value stored for x is a (very good) approximation to the decimal value 1.2, but is not exactly equal to it. On a typical machine, the actual stored value is:

1.0011001100110011001100110011001100110011001100110011 (binary)
which is exactly:

1.1999999999999999555910790149937383830547332763671875 (decimal)
The typical precision of 53 bits provides Python floats with 15–16 decimal digits of accuracy.

For a fuller explanation, please see the floating point arithmetic chapter in the Python tutorial.
Reply
#3
It is a recurrent question. Start by reading this page in the documentation.
Reply
#4
Basic Answers
For financial calculation use decimal module.
from decimal import Decimal

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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Maths and python: Compute stress level cheerful 1 2,705 Oct-20-2021, 10:05 AM
Last Post: Larz60+
  Increasing difficulty of a maths game Maxxy_Gray 1 3,165 Apr-04-2018, 03:00 PM
Last Post: sparkz_alot
  Making maths .py program faster Shutcois 1 2,565 Feb-16-2018, 06:39 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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