python - Floating point precision causes errors during comparison -


i using python 2.7.6. when type interpreter

>>> 0.135-0.027 0.10800000000000001 

whereas should just

0.108 

this causes problem when comparing things, example want compare

>>> 0.135-0.027 <= 0.108 false 

i want give answer true. have use special package handle floats properly? there way fix way? example can force floating division with

from __future__ import division 

is there similar solution problem?

there various things can do, each has own advantages , disadvantages.

the basic problem conversion decimal finite binary representation involves rounding. if use ieee quadruple precision, example, these cases rarer, still occur.

you use decimal library or arbitrary precision library, may unwilling pay cost in runtime using them if have trillions of these calculations.

in case, have ask question, “how accurately really know these numbers?” can consider, “is permissible 0.135-0.027 <= 0.108 considered true?” in cases, answer these “not accurately” , “yes” , problem solved. might uncomfortable solution, it's swings , roundabouts: errors are going occur “both ways” (in sense comparison going fail when should succeed, , going succeed when should fail).

if failing 1 way ok, failing other way absolutely not, can either change rounding mode of hardware (to suit bias want), or can add/subtract ulp (to suit bias want).

for example, consider following (sorry c, i'm sure idea):

double add_ulp(double x) {     union {         double x;         unsigned sign : 1;         unsigned expo : 11;         unsigned long mant : 52;     } inc;     inc.x = x;      inc.mant = 0;     if (inc.expo >= 52 ) {         inc.expo -= 52;         return x+inc.x;     }     return x; } 

you can use this:

if( x-y <= add_ulp(z) ) {     // ... } 

and give answer want in case, bias results in general. if that's bias want, isn't problem, if it's not, it's worse problem have.

hope helps.


Comments

Popular posts from this blog

Android layout hidden on keyboard show -

google app engine - 403 Forbidden POST - Flask WTForms -

c - Why would PK11_GenerateRandom() return an error -8023? -