49 def interpolate (points, x, degree, ycol=1, regions=[], xcol=0):
50 """Polynomial interpolation in a table.
52 points Interpolation table.
53 The x values are in the first column (column 0),
54 and by default, the y values are in the second column (column 1).
55 The x values must be in ascending order, with no duplicates.
56 x The value to interpolate.
57 degree The degree of the interpolating polynomial.
58 ycol The column number of the y values. (0-based.)
59 regions Sometimes, you want to divide the range being interpolated
60 into several distinct regions, where the interpolated
61 function may be discontinuous at the boundaries
62 between regions. To do this, supply this argument,
63 which should contain a list (in ascending order)
64 of the x-coordinates of the region boundaries.
65 When the interpolation runs against a boundary,
66 the algorithm will add a copy of the last point
67 before the boundary, positioned at the boundary.
68 This helps to control runaway extrapolation
69 leading up to the boundary.
70 Returns the interpolated value.
72 The method used is Newtonian interpolation.
73 Based on the cernlib routine divdif.
75 if len (points) < 2
or degree < 1:
76 raise Exception (
'bad args!')
77 degree = min (degree, len (points) - 1)
82 ix = _bisect2 (points, x, xcol)
84 ir = _bisect (regions, x)
94 npts = degree + 2 - (degree%2)
114 while ilo < len (points)
and ir>0
and points[ilo][xcol] < regions[ir-1]:
123 if ihi > len (points):
127 while ihi > 0
and ir<len(regions)
and points[ihi-1][xcol] >= regions[ir]:
138 while ilo < len (points)
and ir>0
and points[ilo][xcol] < regions[ir-1]:
147 if extralo
and points[ilo][xcol] != regions[ir-1]:
152 t.append (regions[ir-1])
153 d.append (points[ilo][ycol])
155 if extrahi
and points[ihi-1][xcol] != regions[ir]:
160 t.append (regions[ir])
161 d.append (points[ihi-1][ycol])
163 t += [points[i][xcol]
for i
in range (ilo, ihi)]
164 d += [points[i][ycol]
for i
in range (ilo, ihi)]
166 degree = min (degree, npts-1)
167 extra = npts != degree+1
170 (t[0], t[npts-2]) = (t[npts-2], t[0])
171 (d[0], d[npts-2]) = (d[npts-2], d[0])
175 for l
in range(0, degree):
177 d[degree+1] = (d[degree+1]-d[degree-1]) / (t[degree+1]-t[degree-1-l])
178 for i
in range (degree, l, -1):
179 d[i] = (d[i]-d[i-1]) / (t[i]-t[i-1-l])
185 sum=0.5*(sum+d[degree+1])
186 for j
in range (degree-1, -1, -1):
187 sum = d[j] + (x - t[j]) * sum