问题
I would like to get piecewise linear function from set of points. Here is visual example:
import matplotlib.pyplot as plt
x = [1,2,7,9,11]
y = [2,5,9,1,11]
plt.plot(x, y)
plt.show()
So I need a function that would take two lists and would return piecewise linear function back. I do not need regression or any kind of least square fit.
I can try to write it myself, but wonder if there is something already written. So far, I only found code returning regression
回答1:
try np.interp. It interpolates the values.
Here is a small example.
>>> import matplotlib.pyplot as plt
>>> import numpy as np
>>> x = [1,2,7,9,11]
>>> y = [2,5,9,1,11]
>>> np.interp([1.5, 3], x, y)
array([ 3.5, 5.8])
A caution note is to make sure for the sample points, make sure the x increases.
来源:https://stackoverflow.com/questions/52953030/how-to-get-piecewise-linear-function-in-python