Search code examples
pythonfunctionsympympmath

Python: symbolic use of hyp2f1 with sympy


In Python, I want to use the hypergeometric function hyp2f1 while keeping at least one symbolic argument. However, there is a TypeError

cannot create mpf from d

where d is the (last) argument of the hypergeometric function.

Someone asked a similar question

sympy and mpmath give "TypeError: cannot create mpf" when using the erf() function within solveset()

after encountering the same problem with the error function erf. The proposed solution was to use the mpmath library instead of the sympy library, but mpmath cannot be used while keeping arguments symbolic.

I also tried to import mpmath and sympy together as proposed in the sympy documentation:

from sympy.mpmath import *

https://docs.sympy.org/0.7.6/modules/mpmath/functions/hypergeometric.html#common-hypergeometric-series

But this is not accepted, as the output is:

ModuleNotFoundError: No module named `sympy.mpmath'

My code is

from sympy import *

d = Symbol('d')

hyp2f1(1,1,1,d)

I hoped to get a simplification to 1/(1-d) or at least hoped that Python can 'store' hyp2f1(1,1,1,d) for symbolic manipulations.

I get an error

TypeError: cannot create mpf from d

The bottom line is, with sympy imported, Python cannot use hyp2f1 with symbolic arguments.


Solution

  • Use the SymPy hyper function:

    In [4]: from sympy import hyper, simplify, Symbol                                                                                 
    
    In [5]: d = Symbol('d')                                                                                                           
    
    In [6]: f = hyper([1, 1], [1], d)                                                                                                 
    
    In [7]: f                                                                                                                         
    Out[7]: 
     ┌─  ⎛1, 1 │  ⎞
     ├─  ⎜     │ d⎟
    2╵ 1 ⎝ 1   │  ⎠
    
    In [8]: simplify(f)                                                                                                               
    Out[8]: 
      1  
    ─────
    1 - d