I want to generate a toy example to illustrate a convex piecewise linear function in python
, but I couldn't figure out the best way to do this. What I want to do is to indicate the number of lines and generate the function randomly.
A convex piecewise-linear function is defined as:
To print this figure:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(x_points,y_points, '-o', label="convex piecewise-linear function")
ax.legend()
fig.patch.set_facecolor('white')
plt.show()
CodePudding user response:
make sure the gradient (=dx/dy) is increasing. Pseudocode:
s = 1;
x = 0;
y = 0;
n = 4;
while(--n>0)
{
//increase x randomly
dx = rand(3);
dy = dx * s;
x = dx;
y = dy;
//increase gradient randomly
s = rand(3);
print x "/" y;
}