I'm trying to use Python to calculate the Rodrigues formula, P_n(x).
http://en.wikipedia.org/wiki/Rodrigues%27_formula
That is, I would like a function which takes into two input parameters, n and x, and returns the output of this formula.
However, I don't think SciPy has this function yet. SpiPy does offer a Legendre module:
http://docs.scipy.org/doc/numpy/reference/routines.polynomials.legendre.html
I don't think any of these is the Rodrigues formula. Am I wrong?
Is there a standard way SciPy offers to do this?
EDIT: I would like the input parameters to be arrays, not just single input values.
If you simply want P_n(x), then you can create a suitable object representing the P_n polynomial using scipy.special.legendre
and call it with your values of x
:
In [1]: from scipy.special import legendre
In [2]: n = 3
In [3]: Pn = legendre(n)
In [4]: Pn(2.5)
Out[4]: 35.3125 # P_3(2.5)
The object Pn
is, in a sense, the "output" of the Rodrigues formula: it is a polynomial of the required order, which can be evaluated at a provided value of x
. If you want a single function that takes n
and x
, you can use eval_legendre
:
In [5]: from scipy.special import eval_legendre
In [6]: eval_legendre(3, 2.5)
Out[6]: 35.3125
As noted in the docs , this is the recommended way to do it for large-ish n
(eg n > 20
), instead of creating a polynomial object with all the coefficients which does not handle rounding errors and numerical stability as well.
EDIT: Both approaches work with arrays (at least for the x
argument). For example:
In [7]: x = np.array([0, 1, 2, 5, 10])
In [8]: Pn(x)
Out[8]:
array([ 0.00000000e+00, 1.00000000e+00, 1.70000000e+01,
3.05000000e+02, 2.48500000e+03])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.