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?
#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


Messages In This Thread
RE: unexpected math resule - by Yoriz - Jun-08-2019, 10:15 AM
RE: unexpected math resule - by Gribouillis - Jun-08-2019, 10:18 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Maths and python: Compute stress level cheerful 1 2,762 Oct-20-2021, 10:05 AM
Last Post: Larz60+
  Increasing difficulty of a maths game Maxxy_Gray 1 3,227 Apr-04-2018, 03:00 PM
Last Post: sparkz_alot
  Making maths .py program faster Shutcois 1 2,660 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