Fast Matlab Code for hypergeometric function $_2F_1$
I am looking for a good numerical algorithm to evaluate the hypergeometric function $_2F_1$ in Matlab (hypergeom
in Matlab is very slow). I looked across the Internet, but did not find anything useful. Does anybody here have an idea where to find a fast algorithm to compute this function?
There is Matlab source code for J. Pearson's master's thesis "Computation of Hypergeometric Functions". The thesis is a available as http://people.maths.ox.ac.uk/porterm/research/pearson_final.pdf and the Matlab code URL is http://people.maths.ox.ac.uk/porterm/research/hypergeometricpackage.zip (I cannot judge the code because I am working with Pascal/Delphi).
A while back I wrote some simple Matlab code to implement the Gaussian Hypergeometric function $_2F_1$: get it here. The code is based on the function's infinite sum representation, which means that it’s only valid inside the complex unit circle, i.e., ${\mid}z{\mid} \lt 1$ (no analytic continuation is performed, but these transformations might be useful if you need to do that). It’s much faster than Matlab’s hypergeom
function (and permits you to specify a tolerance), but you should confirm that it gives satisfactory results (especially for ${\mid}z{\mid} \approx 1$ where you may need to adjust tolerances or increase the number of iterations) in the regime that you're interested in. The code from J. Pearson mentioned in the other answer is nice for learning about various methods and may be useful in other parameter regimes, but it doesn't seem to written with performance in mind – though it may still be faster than full symbolic evaluation using hypergeom
.
Another alternative is to more-efficiently evaluate Matlab’s symbolic hypergeom
itself. You can try my hypergeomq
function (tested in R2016a and R2013b; may require modification to work in earlier versions). This function uses the same underlying compiled code, but performs some optimizations in the conversion from floating-point to symbolic math and back. The speedup for $_2F_1$ probably won't be very dramatic, but for other forms it can be significant (e.g., an order of magnitude speed up for $_2F_2$ in some cases).