Numerics question

2010-07-02 Thread kj




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
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Numerics question

2010-07-02 Thread kj

Please disregard my ineptly posed question.

~K

In i0l9f3$7d...@reader1.panix.com kj no.em...@please.post writes:





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
-- 
http://mail.python.org/mailman/listinfo/python-list