Python插值sin函数使用最近的方法

时间:2017-04-24 18:41:49

标签: python

我使用sin函数的插值,最近的方法编写简单的代码。我的问题是代码是否正确?在我看来,该功能应该由直线组成。生成的图形上会出现曲线。

this article

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

# Original "data set" --- 21 random numbers between 0 and 1.
x0 = np.arange(9)
y0 = [math.sin(i) for i in x0]

plt.plot(x0, y0, 'o', label='Data')
plt.grid(linestyle="-", color=(0.7, 0.8, 1.0))

x = np.linspace(0, 8, len(x0)*2)

# Available options for interp1d
options = ('linear', 'nearest')

f = interp1d(x0, y0, kind='nearest')    # interpolation function
plt.plot(x, f(x), label='nearest')      # plot of interpolated data

plt.legend()
plt.show()

编辑:

我喜欢推动自己的插值算法,我尝试将2个值之和除以2

lst = list(x0)
for i, val in enumerate(lst):
    lst[i] = lst[i] + lst[i+1] / 2

x0 = tuple(lst)

plt.plot(x0, y0, label='nearest')

但它无法正常工作

1 个答案:

答案 0 :(得分:1)

问题是绿线是作为所有点之间的连接图绘制的,并且您的点数太少。也许你误解了np.linspace是如何运作的。如果你增加点数,(并改为仅绘制点而不是连线),你会得到一个看起来更像你可能期望的结果:

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

# Original "data set" --- 21 random numbers between 0 and 1.
x0 = np.arange(9)
y0 = [math.sin(i) for i in x0]

plt.plot(x0, y0, 'o', label='Data')
plt.grid(linestyle="-", color=(0.7, 0.8, 1.0))

x = np.linspace(0, 8, 1000)

# Available options for interp1d
options = ('linear', 'nearest')

f = interp1d(x0, y0, kind='nearest')    # interpolation function
plt.plot(x, f(x), '.', label='nearest')      # plot of interpolated data

plt.legend()
plt.show()