Python Float rounding errors -


this question has answer here:

when using list comprehension expression:

[x * 0.1 x in range(0, 5)] 

i expect list this:

[0.0, 0.1, 0.2, 0.3, 0.4] 

however instead this:

[0.0, 0.1, 0.2, 0.30000000000000004, 0.4] 

what reason behind this?

floats inherently imprecise in pretty every language

if need exact precision use decimal class

from decimal import decimal print decimal("0.3") 

if need them pretty use format strings when displaying eg :

"%0.2f"%2.030000000000034 

if want compare them use threshold

if num1 - num2 < 1e-3 : print "equal enough me!" 

**see abarnert's comments on thresholding ... simplified example more indepth explanation of epsilon thresholding 1 article found 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 detailed explanation)

http://floating-point-gui.de/basic/ (basic tutorial working floats in general)


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -