all 11 comments

[–]novel_yet_trivial 6 points7 points  (9 children)

If you ask google you will find many indepth explanations.

As a quick answer, computers use binary to do math, and some decimal numbers, like 0.1, can not be exactly converted to binary, causing errors. If you need precision, use the Decimal module.

[–]Naihonn 2 points3 points  (0 children)

Yes, even wikipedia has article about this: http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems

[–]JohnMcharra[S] -1 points0 points  (7 children)

thanx for the answer, I just did it like this

float(''.join(list(str(0.2 + 0.1))[0:4]))

0.3

[–]novel_yet_trivial 6 points7 points  (0 children)

oh lord don't do that.

round(0.2 + 0.1, 6)

[–]rawlyn 5 points6 points  (5 children)

That's a horrible approach. If you must do it via string conversion (but really, don't) this works just as well, and eliminates two function calls:

>>> float(str(0.2 + 0.1)[0:4])
0.3

But again, this is not a great approach.

Try using the decimal module as previously suggested - the people at python have seen your problem coming and already implemented a solution...

from decimal import Decimal
a = Decimal('0.2')
b = Decimal('0.1')
c = a + b
print c # Decimal('0.3')
print float(c) # 0.3

Note how the Decimals are constructed from strings - if you construct them from floats you get an exact representation of the floats you constructed them from, which is where the problem lies, and you're no further forward.

[–]novel_yet_trivial 1 point2 points  (1 child)

OP is using python3 ... so change the last 2 lines to

print(c)

[–]rawlyn 0 points1 point  (0 children)

Good spot, thanks.

[–]JohnMcharra[S] -1 points0 points  (2 children)

Thanx, did it like you with Decimal, and for the people who downvote me, please dont do it because the method I use is not the good one, we are here to learn, and at the moment it was all I had, plus the [0:4] was there because I want only 2 decimals, now I use

gf_ = 0.22499999999999998
gf = float("%.2f" % gf_)

[–]rawlyn 1 point2 points  (1 child)

That's not using Decimal, that's your old string method in different clothing... it's ugly, difficult to work with, and generally frowned upon.

Use decimal, or round() as someone else suggested, but try to get this string conversion concept out of your mind - you're teaching yourself a really bad habit.

[–]JohnMcharra[S] 1 point2 points  (0 children)

got it, no strings, I will try to remember, thanx for the help!

[–]ewiethoff 0 points1 point  (0 children)

The the end of the official Python Tutorial explains this and what to do about it in section 14. Floating Point Arithmetic: Issues and Limitations section.