]>
gitweb.michael.orlitzky.com - sage.d.git/blob - mjo/orthogonal_polynomials.py
2 from sage
.symbolic
.expression
import is_Expression
4 def legendre_p(n
, x
, a
= -1, b
= 1):
6 Returns the ``n``th Legendre polynomial of the first kind over the
7 interval [a, b] with respect to ``x``.
9 When [a,b] is not [-1,1], we scale the standard Legendre
10 polynomial (which is defined over [-1,1]) via an affine map. The
11 resulting polynomials are still orthogonal and possess the
12 property that `P(a) = P(b) = 1`.
16 * ``n`` -- The index of the polynomial.
18 * ``x`` -- Either the variable to use as the independent
19 variable in the polynomial, or a point at which to evaluate
22 * ``a`` -- The "left" endpoint of the interval. Must be a real number.
24 * ``b`` -- The "right" endpoint of the interval. Must be a real number.
28 If ``x`` is a variable, a polynomial (symbolic expression) will be
29 returned. Otherwise, the value of the ``n``th polynomial at ``x``
34 We should agree with Maxima for all `n`::
36 sage: eq = lambda k: bool(legendre_p(k,x) == legendre_P(k,x))
37 sage: all([eq(k) for k in range(0,20) ]) # long time
40 We can evaluate the result of the zeroth polynomial::
42 sage: f = legendre_p(0,x)
46 We should have |P(a)| = |P(b)| = 1 for all a,b::
48 sage: a = RR.random_element()
49 sage: b = RR.random_element()
50 sage: k = ZZ.random_element(20)
51 sage: P = legendre_p(k, x, a, b)
52 sage: abs(P(x=a)) # abs tol 1e-12
54 sage: abs(P(x=b)) # abs tol 1e-12
57 Two different polynomials should be orthogonal with respect to the
58 inner product over [a,b]::
60 sage: a = RR.random_element()
61 sage: b = RR.random_element()
62 sage: j = ZZ.random_element(20)
64 sage: Pj = legendre_p(j, x, a, b)
65 sage: Pk = legendre_p(k, x, a, b)
66 sage: integrate(Pj*Pk, x, a, b) # abs tol 1e-12
69 The first few polynomials shifted to [0,1] are known to be::
73 sage: p2 = 6*x^2 - 6*x + 1
74 sage: p3 = 20*x^3 - 30*x^2 + 12*x - 1
75 sage: bool(legendre_p(0, x, 0, 1) == p0)
77 sage: bool(legendre_p(1, x, 0, 1) == p1)
79 sage: bool(legendre_p(2, x, 0, 1) == p2)
81 sage: bool(legendre_p(3, x, 0, 1) == p3)
86 raise TypeError('n must be a natural number')
89 raise ValueError('n must be nonnegative')
91 if not (a
in RR
and b
in RR
):
92 raise TypeError('both `a` and `b` must be real numbers')
96 n
= ZZ(n
) # Ensure that 1/(2**n) is not integer division.
100 # This is an affine map from [a,b] into [-1,1] and so preserves
102 return (2 / (b
-a
))*t
+ 1 - (2*b
)/(b
-a
)
105 return binomial(n
,m
)*binomial(n
, n
-m
)
108 # As given in A&S, but with `x` replaced by `phi(x)`.
109 return ( ((phi(x
) - 1)**(n
-m
)) * (phi(x
) + 1)**m
)
111 # From Abramowitz & Stegun, (22.3.2) with alpha = beta = 0.
112 P
= dn
* sum([ c(m
)*g(m
) for m
in range(0,n
+1) ])
114 # If `x` is a symbolic expression, we want to return a symbolic
115 # expression (even if that expression is e.g. `1`).