Skip to content

Instantly share code, notes, and snippets.

@dmitrybubyakin
Created October 21, 2016 08:53
Show Gist options
  • Save dmitrybubyakin/6edcdebbd0587a23f8a5c34e2b36363f to your computer and use it in GitHub Desktop.
Save dmitrybubyakin/6edcdebbd0587a23f8a5c34e2b36363f to your computer and use it in GitHub Desktop.
import numpy as np
import matplotlib.pyplot as plt
x_for_f = np.linspace(-1.5, 1.5, 500)
y_for_f = np.array([np.tan(x_for_f[i]) for i in range(len(x_for_f))], dtype = float)
print("Enter count:")
n = int(input())
x = np.linspace(-1.5, 1.5, num = n)
y = np.array([np.tan(x[i]) for i in range(len(x))], dtype = float)
x_cheb = np.array([(3/2)*np.cos((2*i+1)/(2*n+2)*np.pi) for i in range(n+1)], dtype = float)
y_cheb = np.array([np.tan(x_cheb[i]) for i in range(len(x_cheb))], dtype = float)
def lagranz(x,y,t):
z = 0
for j in range(len(y)):
p1=1
p2=1
for i in range(len(x)):
if i == j:
p1 *=1
p2 *=1
else:
p1 *= (t-x[i])
p2 *= x[j]-x[i]
z = z+y[j]*p1/p2
return z
xnew = []
ynew = [lagranz(x,y,i) for i in xnew]
x_cheb_new = np.linspace(np.min(x_cheb), np.max(x_cheb), 100)
y_cheb_new = [lagranz(x_cheb, y_cheb, i) for i in x_cheb_new]
y_dev = np.array([y_for_f[i] - ynew[i] for i in range(len(xnew))], dtype = float)
y_dev_cheb = np.array([y_for_f[i] - y_cheb_new[i] for i in range(len(x_cheb_new))], dtype = float)
plt.xlabel(r'$x$')
plt.ylabel(r'$f(x)$')
plt.title(r'$f(x)=2+sin(x)$')
plt.plot(x_for_f, y_for_f, label = "f(x)=2+sin(x)")
plt.plot(x, y, 'o', xnew, ynew, label = "g(x), equidistant nodes")
plt.plot(x_cheb, y_cheb, 'o', x_cheb_new, y_cheb_new, label = "h(x), Chebyshev nodes")
plt.plot(xnew, y_dev, "--", label = "f(x)-g(x)")
plt.plot(x_cheb_new, y_dev_cheb, "-.", label = "f(x)-h(x)")
plt.legend()
plt.grid(True)
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment