Reputation: 3340
I write simple code using interpolation of sin function, nearest method. My question is it's that code it's correct? It seems to me that the function should consist of straight lines. Curved lines appear on the generated graph.
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()
EDIT:
I woudl like to impelment own interpolation algorithm, I try to divide sum of 2 values by 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')
But it's not working correctly
Upvotes: 1
Views: 2279
Reputation: 6891
The problem is that the green line is drawn as a connected graph between all the points, and you have too few points. Maybe you have misunderstood how np.linspace
works. If you increase the number of points, (and change to plot only the points instead as connected lines) you will get a result that looks much more like you probably expect:
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()
Upvotes: 1