Skip to content

Instantly share code, notes, and snippets.

@ceptreee
Created September 22, 2018 01:58
Show Gist options
  • Save ceptreee/821cff978e098409f194eb87ad19d984 to your computer and use it in GitHub Desktop.
Save ceptreee/821cff978e098409f194eb87ad19d984 to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sb
def Chebyshev(N):
P = [0]*(N+1)
P[0] = 1
P[1] = x
for n in range(1,N):
P[n+1] = 2 * x*P[n] - P[n-1]
P[n+1] = sb.expand(P[n+1])
p = [0]*(N+1)
for n in range(N+1):
p[n] = sb.lambdify(x,P[n])
return P,p
def Legendre(N):
P = [0]*(N+1)
P[0] = 1
P[1] = x
for n in range(1,N):
P[n+1] = ( (2*n+1)*x*P[n] - n*P[n-1]) /(n+1)
P[n+1] = sb.expand(P[n+1])
p = [0]*(N+1)
for n in range(N+1):
p[n] = sb.lambdify(x,P[n])
return P,p
x = sb.Symbol('x')
N = 6
P1,p1 = Chebyshev(N)
P2,p2 = Legendre(N)
xx = np.linspace(-1,1,1000)
YY1 = []
YY2 = []
for n in range(N):
yy = p1[n](xx)
YY1.append(yy)
yy = p2[n](xx)
YY2.append(yy)
plt.close('all')
plt.figure(figsize=(8,8))
plt.subplot(2,1,1)
for n in range(N):
if isinstance(YY1[n],np.ndarray) is False:
YY1[n] = YY1[n]*np.ones_like(xx)
plt.plot(xx,YY1[n],label='$T_%d(x) = %s$' %(n,sb.latex(P1[n])))
plt.title('Chebyshev Polynomials (1st)',fontsize=12)
plt.subplot(2,1,2)
for n in range(N):
if isinstance(YY2[n],np.ndarray) is False:
YY2[n] = YY2[n]*np.ones_like(xx)
plt.plot(xx,YY2[n],label='$P_%d(x) = %s$' %(n,sb.latex(P2[n])))
plt.title('Legendre Polynomials',fontsize=12)
axes = plt.gcf().get_axes()
for axis in axes:
plt.sca(axis)
plt.grid()
plt.xlabel('$x$')
plt.ylabel('$y$')
plt.ylim([-1.2,1.2])
plt.legend(fontsize=12,bbox_to_anchor=(1.04,0.8), loc="upper left")
plt.tight_layout()
plt.savefig('ChebyshevPolynomials2.png')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment