inter_1.py 997 字节
Newer Older
F
feilong 已提交
1
# -*- coding: UTF-8 -*-
F
feilong 已提交
2
# 作者:huanhuilong
F
feilong 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
# 标题:Python 插值
# 描述:封装一个便利的插值函数,支持 线性插值、三次插值、样条曲线 三种类型


import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt


def easy_inter(x, y, sample_count, kind):
    f = None
    if kind == 'linear':
        f = interpolate.interp1d(x, y, kind='linear')
    elif kind == 'cubic':
        f = interpolate.interp1d(x, y, kind='cubic')
    elif kind == 'spline':
        f = interpolate.UnivariateSpline(x, y)
    else:
        return None

    x = np.linspace(x.min(), x.max(), sample_count)
    y = f(x)
    return x, y


if __name__ == "__main__":
    x = np.linspace(-12, 12, 10)
    y = np.cos(x)+np.sin(x)
    plt.plot(x, y, 'o')

    x, y = easy_inter(x, y, 20, "linear")
    plt.plot(x, y, '-')

    x, y = easy_inter(x, y, 20, "cubic")
    plt.plot(x, y, '--')

    x, y = easy_inter(x, y, 20, "spline")
    plt.plot(x, y, ':')

    plt.show()