7

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.

Gareth McCaughan
  • 19,888
  • 1
  • 41
  • 62
Rohan
  • 1,705
  • 7
  • 17
  • 38
  • why are you even converting the result of a float subtraction to a float? what would you expect it to be other then a float? – mata May 01 '12 at 21:09
  • @duffymo: im new to python and never saw this coming. always better to ask rather than commit silly mistakes :) – Rohan May 02 '12 at 04:46
  • Yeah, I agree. No need to make people feel bad for asking a question about an implementation detail that's actually pretty arcane when you think about it. – Andrew Gorcester May 02 '12 at 17:50

3 Answers3

16

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.

Gareth Latty
  • 86,389
  • 17
  • 178
  • 183
  • Thanks.. was looking for this. Answers my question – Rohan May 01 '12 at 19:56
  • You have greatly alleviated my pain. I thought it was a bug at first, but it looked way too perfectly inaccurate to not be a mathematical mistake related to python type logic. – Alex Gurrola Jun 26 '17 at 08:14
4

You can use round()

for example:

print(round(10 - 9.2, 2))
0

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.

Andrew Gorcester
  • 19,595
  • 7
  • 57
  • 73
  • 2
    Of course, `decimal` also implemented floating point numbers, just with a different base - meaning, you still get inaccuracies, just the ones people are used to. –  May 01 '12 at 19:57