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