在Sympy中表现阶乘

时间:2018-07-18 10:27:56

标签: sympy

我有以下符合预期的Sympy代码:

import numpy as np
from sympy.utilities.lambdify import lambdify
from sympy.core import sympify
from sympy import factorial

ex = sympify('-x**2 / cos(x)')
flam = lambdify(['x'], ex, "numpy")
flam(np.array(range(5)))

这将返回:

array([ 0.        , -1.85081572,  9.61199185,  9.09097799, 24.4781705 ])

现在,我需要知道的是如何对阶乘进行相同的处理,即使用factorial(x)而不是cos(x)。代码:

ex = sympify('-x**2 / factorial(x)')
flam = lambdify(['x'], ex, "numpy")
flam(np.array(range(5)))

引发NameError

NameError: global name 'factorial' is not defined

我应该使用什么字符串,以便将其转换为可以在lambdify之后求值的阶乘?

在此先感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

通过修补,我获得了以下代码。似乎numpy阶乘函数不适用于ndarrays ...

import numpy as np
from sympy.utilities.lambdify import lambdify

flam = lambdify(['x'], '-x**2 / cos(x)', "numpy")
flam(np.array(range(5)))

# >>> array([ 0.        , -1.85081572,  9.61199185,  9.09097799, 24.4781705 ])


import scipy.special

flam = lambdify('x', 'factorial(x)', ['numpy', {'factorial':scipy.special.factorial}])
flam(np.array(range(5)))

# >>> array([ 1.,  1.,  2.,  6., 24.])