I think I could figure this out eventually, but I'm hoping it will be a very easy question for someone out there. I would like to convert the following function to cython to be as fast as possible. I am not sure exactly what I need to import from mpmath to do that.
Here is the function:
A good test case would be myfisher_mp(1286, 9548, 133437, 148905), which takes about 1 second on my desktop. The inputs a1,a2,b1,b2 can be assumed to be positive ints.
Actually, there is a simple method to speed this up quite significantly. Since the only needed gamma values are at integers (up to a few several thousand), you can just store all of them in a list or a dict.
In fact mpmath provides a decorator "memoize" that effectively does this. So you could just add
gamma = memoize(gamma)
to the program. With this change, the test case myfisher_mp(1286, 9548, 133437, 148905) runs about 2x faster the first time, and 7x faster the second time. But it should be even faster if you precompute the needed gamma values and replace the function calls with list lookups. Note that to precompute a list up to say n = 100000, you could just use a loop instead of repeatedly calling gamma, and this would be very fast.
Assuming you mean convert this function to Cython [ah, you do, it's only the title that's wrong-- edited], I'm not sure whether it will help.
First, I get
Is that right? Almost all of the computations in the loops over i in the function don't matter to the final value because they're too small.
Second, you only get real benefits from Cython when the work can be pushed into C. If the values are so small, though, C floats won't work, as they'll underflow. And it's not that most of the time is being spent in the Python loops, which are linear anyway: the vast majority of the time is being spent in the gamma function itself, which is already pretty fast.
Do you have a link to the definition of this function? I'm sure we can find a way to compute it more efficiently, especially given how many terms are currently noncontributing.
Use a recurrence instead of computing each term from scratch. The quotient between successive values of hyp_mp should be a rational function of i.
To avoid manual labor, I would usually use Mathematica to rewrite a hypergeometric quotient to rational form. I'm not sure if Sage currently has direct support for this.
posted Mar 04 '11fredrik
31 ● 3
Asked: Mar 04 '11
Seen: 202 times
Last updated: Mar 05 '11
powered by ASKBOT version 0.7.22
Copyright Sage, 2010. Some rights reserved under creative commons license.