floating point in python gives a wrong answer

I calculated the following:

>>> float(10.0-9.2)
0.800000000000000*7*

even doing 10.0-9.2 gave the above result. Why is the extra 7 coming in the result?

I’m on python 3.2.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Floating point arithmetic has built-in problems as it’s based on a binary approximation of numbers.

There is a good explanation of this in the Python docs.

You can check out the decimal module if you need more exact answers.

Method 2

You can use round()

for example:

print(round(10 - 9.2, 2))

Method 3

This is typical of binary floating-point arithmetic on all platforms. If your application is not tolerant of rounding errors within this margin of error, you can use Decimal objects instead.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x