Numerics question

kj no.email at please.post
Fri Jul 2 14:00:03 EDT 2010





I define

ninv = 1.0/n

...where n is some integer, and I want to write some function f such
that f(m * ninv) returns the smallest integer that is >= m * ninv,
where m is some other integer.  And, in particular, if m is p*n
for some integer p, then f((p*n) * ninv) should return the integer
p.

The first solution that comes to mind is something like

def f(x):
    return int(math.ceil(x))

At first this seems to work:

>>> f((7*2) * (1.0/2))
7
>>> f((7*3) * (1.0/3))
7

...but there are values of n for which it fails:

>>> f((7*75) * (1.0/75))
8

The problem here is that, due to numerical error, the expression
((7*75) * (1.0/75)) evaluates to a number *just* above 7.  The
surrounding math.ceil then turns this into 8.0, etc.

Is there a way to define f so that it behaves as expected?

TIA!

~K



More information about the Python-list mailing list