How to implement linear interpolation?

后端 未结 7 1351
暗喜
暗喜 2020-11-28 08:16

Say I am given data as follows:

x = [1, 2.5, 3.4, 5.8, 6]
y = [2, 4, 5.8, 4.3, 4]

I want to design a function that will interpolate linearl

7条回答
  •  伪装坚强ぢ
    2020-11-28 08:47

    Building on Lauritz` answer, here's a version with the following changes

    • Updated to python3 (the map was causing problems for me and is unnecessary)
    • Fixed behavior at edge values
    • Raise exception when x is out of bounds
    • Use __call__ instead of __getitem__
    from bisect import bisect_right
    
    class Interpolate:
        def __init__(self, x_list, y_list):
            if any(y - x <= 0 for x, y in zip(x_list, x_list[1:])):
                raise ValueError("x_list must be in strictly ascending order!")
            self.x_list = x_list
            self.y_list = y_list
            intervals = zip(x_list, x_list[1:], y_list, y_list[1:])
            self.slopes = [(y2 - y1) / (x2 - x1) for x1, x2, y1, y2 in intervals]
    
        def __call__(self, x):
            if not (self.x_list[0] <= x <= self.x_list[-1]):
                raise ValueError("x out of bounds!")
            if x == self.x_list[-1]:
                return self.y_list[-1]
            i = bisect_right(self.x_list, x) - 1
            return self.y_list[i] + self.slopes[i] * (x - self.x_list[i])
    

    Example usage:

    >>> interp = Interpolate([1, 2.5, 3.4, 5.8, 6], [2, 4, 5.8, 4.3, 4])
    >>> interp(4)
    5.425
    

提交回复
热议问题