When using list comprehension expression:
[x * 0.1 for x in range(0, 5)]
I expect to get a list like this:
[0.0, 0.1, 0.2, 0.3, 0.4]
However I instead I get this:
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4]
What is the reason behind this?
When using list comprehension expression:
[x * 0.1 for x in range(0, 5)]
I expect to get a list like this:
[0.0, 0.1, 0.2, 0.3, 0.4]
However I instead I get this:
[0.0, 0.1, 0.2, 0.30000000000000004, 0.4]
What is the reason behind this?
floats are inherently imprecise in pretty much every language
if you need exact precision use the Decimal class
from decimal import Decimal
print Decimal("0.3")
if you just need them to look pretty just use format strings when displaying eg :
"%0.2f"%2.030000000000034
if you want to compare them use some threshold
if num1 - num2 < 1e-3 : print "Equal Enough For Me!"
**see abarnert's comments on thresholding ... this is a very simplified example for a more indepth explanation of epsilon thresholding one article I found is here http://www.cygnus-software.com/papers/comparingfloats/Comparing%20floating%20point%20numbers.htm
Additional Reading:
http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html (for a detailed explanation)
http://floating-point-gui.de/basic/ (basic tutorial for working with floats in general)
float(1<<64)+.1 == float(1<<64) is True—it's not even accurate to 1 place after the decimal.num1 - num2 < 1e-3 * max(num1, num2) (or gmean or some other function, depending on the case). And of course this only works for positive numbers, because you forgot the abs. I think it would be better to link to some discussion of epsilon thresholding or error analysis than to try to explain it in one line.List comprehension does not matter.
>>> 3 * 0.1
0.30000000000000004
>>> 2 * 0.1
0.2
>>> 0.1 + 0.2
0.30000000000000004
More information about Python float and floating point arithmetic - here
The list comprehension is irrelevant, this is purely an issue with floating-point numbers. For an extremely detailed answer you should give this article a read: http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html