Skip to content

Instantly share code, notes, and snippets.

@ceptreee
Last active September 13, 2018 12:22
Show Gist options
  • Save ceptreee/80c703f007c22feeb40979211111fb7b to your computer and use it in GitHub Desktop.
Save ceptreee/80c703f007c22feeb40979211111fb7b to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
import sympy as sb
x = sb.Symbol('x')
def Chebyshev1st(N):
T = [0]*(N+1)
T[0] = 1
T[1] = x
for n in range(1,N):
T[n+1] = 2 * x*T[n] - T[n-1]
T[n+1] = sb.expand(T[n+1])
return T
N = 5
T = Chebyshev1st(N)
xx = np.linspace(-1,1,1000)
YY = []
for n in range(N):
f = T[n]
f = sb.lambdify(x,f)
yy = f(xx)
YY.append(yy)
plt.close('all')
plt.figure(figsize=(8,4))
for n in range(N):
if isinstance(YY[n],np.ndarray) is False:
YY[n] = YY[n]*np.ones_like(xx)
plt.plot(xx,YY[n],label='$T_%d(x) = %s$' %(n,sb.latex(T[n])))
plt.title('Chebyshev Polynomials (1st)',fontsize=12)
plt.grid()
plt.xlabel('x')
plt.ylabel('y')
plt.legend(fontsize=12,bbox_to_anchor=(1.04,0.8), loc="upper left")
plt.tight_layout()
plt.savefig('ChebyshevPolynomials_1st.png')
import numpy as np
import matplotlib.pyplot as plt
import sympy as sb
x = sb.Symbol('x')
def Chebyshev1st(N):
T = [0]*(N+1)
T[0] = 1
T[1] = x
for n in range(1,N):
T[n+1] = 2 * x*T[n] - T[n-1]
T[n+1] = sb.expand(T[n+1])
return T
def Chebyshev2nd(N):
T = [0]*(N+1)
T[0] = 1
T[1] = 2*x
for n in range(1,N):
T[n+1] = 2 * x*T[n] - T[n-1]
T[n+1] = sb.expand(T[n+1])
return T
N = 5
T1 = Chebyshev1st(N)
T2 = Chebyshev2nd(N)
xx = np.linspace(-1,1,1000)
YY1 = []
YY2 = []
for n in range(N):
f1 = T1[n]
f1 = sb.lambdify(x,f1)
yy = f1(xx)
YY1.append(yy)
f2 = T2[n]
f2 = sb.lambdify(x,f2)
yy = f2(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(T1[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='$U_%d(x) = %s$' %(n,sb.latex(T2[n])))
plt.title('Chebyshev Polynomials (2nd)',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