# Builtin Float Epsilon? (was: Re: Does python suck or I am just stupid? )

Gerrit Holl gerrit at nl.linux.org
Sun Feb 23 17:52:43 CET 2003

```djw schreef op zaterdag 22 februari om 19:43:06 +0000:
> >
> >http://www.python.org/cgi-bin/faqw.py?req=show&file=faq04.098.htp
> >
> >(Then change the u==x comparison from a strict equality check, as
> >prescribed therein.)
> >
> >-Peter
>
> I've always wondered, given this fact, why is there an equivalence
> operator for floats? (or, maybe the == operator should do the epsilon
> range check for you somehow). It seems to be strange to have an valid
> operator for a type that you should never in practice use. Maybe you
> should be able to write something like:
>
> sys.floatepsilon = 0.000000001 # or maybe some nice default value
>
> ...
> u = 1.0000000000001
> v = 1.0
>
> if u == v: # uses the system float epsilon test instead of "true" test
> 	...
>
> Seems like this would keep more people from running into this 'problem'.

I think this is enough:

9 >>> class Myfloat(float):
9 ...  epsilon = 0.001
9 ...  def __cmp__(self, other):
9 ...   if abs(self-other)<self.epsilon: return 0
9 ...   else: return float.__cmp__(self, other)
9 ...
10 >>> Myfloat(10) == Myfloat(10)
True
11 >>> Myfloat(10) == Myfloat(11)
False
12 >>> Myfloat(10) == Myfloat(10.01)
False
13 >>> Myfloat(10) == Myfloat(10.0001)
True

yours,
Gerrit.

--
Asperger Syndroom - een persoonlijke benadering:
http://people.nl.linux.org/~gerrit/
Het zijn tijden om je zelf met politiek te bemoeien:
http://www.sp.nl/

```