How to get piecewise linear function in Python

十年热恋 提交于 2021-01-28 10:46:37

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!