Saturday, May 2, 2015

Why are floating point calculations so inaccurate? - Python Numbers - Python Tutorial

Why are floating point calculations so inaccurateWhy are floating point calculations so inaccurate?


This may be deeper than you are ready to go at this point in learning Python but it is important to understand that floating point numbers may not be returned as you expect with performing calculations in Python. To kick off this tutorial let’s take a look at an example of this weird problem you may come across in Python.


Example of Floating Point Calculations


#Example of Floating Point Calculations

>>> 7.6 + 8.7
16.299999999999997

7.6 + 8.7 should equal 16.3 correct?  Why does Python have this bug?  It is not a bug actually. This is related to the underlying c language which Python is built on. This issue can seen in a lot of computer programming languages not just in Python.


Why Does This Happen?


This happens when the c language attempts to represent floating point numbers. C language uses binary numbers to account for floating point numbers but these numbers sometimes return numbers with a small round off error. Floating point numbers are actually handled as fractions then converted to floating point numbers when displayed. The conversion from a fraction to a floating point number is not so accurate as you may like.


How Can I Make My Floating Point Numbers More Accurate?


We have two options.  We could use round() which is a built-in function or we could use the decimal module. We will cover the built-in round() function in the next tutorial and then the following tutorial we will cover the decimal module. We will see how to work around this issue within Python.


In conclusion


We saw how floating point numbers are represented in Python and that it is not an issue with Python but an issue with how the underlying c language represents floating point numbers. We now know that floating point numbers are broken down into fractions and then returned to us as floating point numbers where fractions are not as accurate as floating point numbers. This will give us a slight rounding issue with our floating point numbers.  There are ways to be more exact by either using a built-in function called round or by using a module called decimal. Now that you understand that Why are floating point calculations so inaccurate in Python we can safely say we are moving in the right direction to learn programming.



No comments:

Post a Comment