5 This returns a polynom that fits the points specified in the input
6 dictionary (lagrange interpolation). In this dictionary, the keys
7 are x value and the values are y corresponding values
8 (i.e. y=polynom(x)). The polynom is a scipy polynom and then is a
9 callable (can be used as a function).
11 tmp = scipy.poly1d([0])
12 result=scipy.poly1d([0])
14 for i in points.keys():
15 numerator=scipy.poly1d([1])
17 for j in points.keys():
19 tmp = scipy.poly1d([1,-j])
20 numerator = numerator * tmp
21 denom = denom * (i - j)
22 tmp = (numerator/denom) * points.get(i)
27 def points_usingfunction(arrX,function):
30 points[x] = function(x)
33 def points_usingarray(arrX,arrY):
35 for i in range(len(arrX)):
42 # Sort this dictionary by keys and returns 2 lists, the list of X
43 # and the list of Y, the whole ordered by X
46 return keys, [points[key] for key in keys]
50 def plot(function, start=0., stop=1., step=0.01):
52 The parameter function must be a callable.
54 arrX=numpy.arange(start, stop, step, dtype='float64')
55 # function is a callable
56 arrY=map(function,arrX)
57 pylab.plot(arrX, arrY)
62 # The points does not need to be ordered by x values
63 def TEST_lagrange_01():
64 input = {0.:5, 0.2:10, 0.9:10, 0.6:21, 1:8}
65 polynom = lagrange(input)
67 plot(function=polynom, start=0., stop=1., step=0.001)
69 def TEST_lagrange_02():
70 input = {0.:0., 0.5:1., 1.:0.}
71 polynom = lagrange(input)
73 plot(function=polynom, start=0., stop=1., step=0.001)
76 # One can create the input dictionary from arrays
77 def TEST_lagrange_usingarrays_01():
78 arrX = [0., 0.2, 0.9, 0.6, 1]
79 arrY = [5, 10, 10, 21, 8]
80 input = points_usingarray(arrX,arrY)
81 polynom = lagrange(input)
83 plot(function=polynom, start=0., stop=1., step=0.001)
85 # Another example using numpy
86 def TEST_lagrange_usingarrays_02():
87 arrX=numpy.arange(start=0., stop=1., step=0.1, dtype='float64')
88 arrY=numpy.zeros(len(arrX), dtype='float64')
90 input = points_usingarray(arrX,arrY)
91 polynom = lagrange(input)
93 plot(function=polynom, start=0., stop=1., step=0.001)
96 # One can create the input dictionary from a function applied to an
99 # simple method for mathematical functions
100 def TEST_lagrange_usingfunction_01():
101 arrX=numpy.arange(start=0., stop=1., step=0.1, dtype='float64')
102 arrY=numpy.cos(10*arrX)
103 input = points_usingarray(arrX,arrY)
104 polynom = lagrange(input)
106 plot(function=polynom, start=0., stop=1., step=0.001)
117 def TEST_lagrange_usingfunction_01():
118 arrX=numpy.arange(start=0., stop=1., step=0.1, dtype='float64')
119 input = points_usingfunction(arrX,chapeau)
120 polynom = lagrange(input)
122 plot(function=polynom, start=0., stop=1., step=0.001)
125 if __name__ == "__main__":
128 #TEST_lagrange_usingarrays_01()
129 #TEST_lagrange_usingarrays_02()
130 #TEST_lagrange_usingfunction_01()
131 #TEST_lagrange_usingfunction_01()