Search code examples
pythonpiecewise

How to get piecewise linear function in Python


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()

piecewise illustration

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


Solution

  • 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.