# a little math problem

John Hunter jdhunter at ace.bsd.uchicago.edu
Fri Apr 16 21:05:46 CEST 2004

```>>>>> "Jeff" == Jeff Epler <jepler at unpythonic.net> writes:

Jeff> math.fmod might help Jeff

Doesn't seem to. Eg,

>>> 25.2%.2
0.1999999999999979
>>> math.fmod(25.2,2)
1.1999999999999993
>>> math.fmod(25.2,.2)
0.1999999999999979

Here is what I have so far - hasn't solved the floating point problem
though

class Base:
'this solution has floating point inaccuracies'
def __init__(self, base):
assert(base>0)
self.base = base

def lt(self, x):
'return the largest multiple of base < x'
d,m = divmod(x, self.base)
if m==0: return (d-1)*self.base
else: return d*self.base

def le(self, x):
'return the largest multiple of base <= x'
d,m = divmod(x, self.base)
return d*self.base

def gt(self, x):
'return the largest multiple of base > x'
d,m = divmod(x, self.base)
return (d+1)*self.base

def ge(self, x):
'return the largest multiple of base >= x'
d,m = divmod(x, self.base)
if m==0: return x
return (d+1)*self.base

def get_base(self):
return self.base

def closeto(x,y):
print x,y,abs(x-y), abs(x-y) < 1e-12

b = Base(.2)

closeto(b.lt(25.3), 25.2)
closeto(b.lt(25.2), 25.0)
closeto(b.le(25.3), 25.2)
closeto(b.le(25.2), 25.2)

print
closeto(b.gt(25.3), 25.4)
closeto(b.gt(25.2), 25.4)
closeto(b.ge(25.3), 25.4)
closeto(b.ge(25.2), 25.2)

print
print

b = Base(4)

closeto(b.lt(12), 8)
closeto(b.lt(13), 12)
closeto(b.le(12), 12)
closeto(b.le(13), 12)

print

closeto(b.gt(12), 16)
closeto(b.gt(13), 16)
closeto(b.ge(12), 12)
closeto(b.ge(13), 16)

```