from numpy import * from matplotlib.pyplot import * from scipy.interpolate import lagrange def chebyshev(min, max, n): k = arange(0, n) return min + (max-min) * 0.5 * (cos(pi*(2.*k+1.)/(2.*n)) + 1.0) def f(x): return sin(x) x5 = chebyshev(0, 2.*pi, 5) fp5 = lagrange(x5, f(x5)) x10 = chebyshev(0, 2.*pi, 10) fp10 = lagrange(x10, f(x10)) x15 = chebyshev(0, 2.*pi, 15) fp15 = lagrange(x15, f(x15)) x = linspace(0, 2.*pi, 1000) figure() plot(x, f(x), label='f(x)') plot(x, fp5(x), label='5th degree') plot(x, fp10(x), label='10th degree') plot(x, fp15(x), label='15th degree') legend() def g(x): return 1/(1+x*x) x5 = chebyshev(-5, 5., 5) gp5 = lagrange(x5, g(x5)) x10 = chebyshev(-5, 5, 10) gp10 = lagrange(x10, g(x10)) x15 = chebyshev(-5, 5., 15) gp15 = lagrange(x15, g(x15)) x = linspace(-5, 5, 1000) figure() plot(x, g(x), label='g(x)') plot(x, gp5(x), label='5th degree') plot(x, gp10(x), label='10th degree') plot(x, gp15(x), label='15th degree') legend() def h(x): return x**-12 - x**-6 x5 = chebyshev(1, 5., 5) hp5 = lagrange(x5, h(x5)) x10 = chebyshev(1, 5, 10) hp10 = lagrange(x10, h(x10)) x15 = chebyshev(1, 5., 15) hp15 = lagrange(x15, h(x15)) x = linspace(1, 5, 1000) figure() plot(x, h(x), label='h(x)') plot(x, hp5(x), label='5th degree') plot(x, hp10(x), label='10th degree') plot(x, hp15(x), label='15th degree') legend() show()