class Interpolator: """Provides linear interpolation for functions y=f(x)""" def __init__(self,xs,fs): """Create an interpolator using the list of anchor points xs and their values fs for the interpolation.""" if len(xs) != len(fs): raise Exception('Lists were not the same length.') self.data = sorted(zip(xs,fs)) # '_' can be used to indicate that a tuple value is not used self.minX, _ = self.data[0] self.maxX, _ = self.data[-1] def f(self,x): """Return the linearly interpolated value f(x) from the whole range spanned by the xs.""" if x < self.minX or x > self.maxX: raise Exception('Cannot extrapolate outside x range %s.' % ((self.minX, self.maxX),)) ### FIX THIS FUNCTION (Q.3b) ### # find enclosing pair of values left=(x0,f0) right=(x1,f1) # where x0 < x < x1 left = self.data[-2] right = self.data[-1] # linearly interpolate between neighbouring points return self.interpolate(x, left, right) def interpolate(self,x,left,right): """Interpolate the value of f(x) given left=(x0,y0) and right=(x1,y1) anchor points.""" x0, y0 = left x1, y1 = right ### FIX THIS FUNCTION (Q.3a) ### return y0 if __name__ == '__main__': import numpy, pylab # create anchor points from a sin() function xs = numpy.arange(-5,5,0.8) fs = numpy.sin(xs) # create interpolator ip = Interpolator(xs,fs) # plot the function with steps inbetween the anchor points x = numpy.arange(min(xs),max(xs),0.1) y = [ ip.f(xx) for xx in x ] pylab.plot(x,y,'.') pylab.show()