django - Python floating point issue? -


verison 2.6.5 if helps. so, i'm doing stuff in django , grabbing value floatfield. , comparing floatfield. let's call these 2 x , y. x ends 35.0 when run it. y ends 35.0 when run it.

35.0 > 35.0 # false, ok no worries x > y # true, why? round(x) > round(y) # false, ok looks have round 

i know float has issues during calculation in case, values 2 variables displayed 35.0 thought 35.0. mean python might not show information behind float object? know common question if 35.000000001 or something, python not display entire value?

edit: ok, read through this. floating point life problems solved me lol. http://docs.python.org/2/tutorial/floatingpoint.html

python rounds off floating point values when printing/representing them,* not while comparing them.

try this:

'{:.17f} {:.17f}'.format(x, y) 

(since floats have on 17 significant digits of precision, , number in range [10, 100), printing 17 digits should enough see of details exist. if you're not sure how calculate it, toss on digits: {:.64f} legal.)

alternatively, convert them decimal objects high-enough precision represent difference, or many other things.

or, simply, x > y test whether x greater y, if that's want know.


for real-life code, if want know if 2 float values resulted 2 different computations "the same", can't that. ideally, need proper error analysis. failing that, epsilon calculation (abs(x-y) < epsilon if care fixed scale, or abs((x-y) / (x+y)) < epsilon if have no idea scale might be) enough. x == y never enough.


* details differ between different python versions. example, try this:

>>> str(1.000000000000001), repr(1.000000000000001) 

in python 2.7, get:

'1.0', '1.000000000000001' 

but in python 3.3:

'1.000000000000001', '1.000000000000001' 

Comments

Popular posts from this blog

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

keyboard - C++ GetAsyncKeyState alternative -

android - java.net.UnknownHostException(Unable to resolve host “URL”: No address associated with hostname) -