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:
For instance, if I want to have four linear lines, then I want to generate something as shown below.
Since there are four lines. I need to generate four increasing random integers to determine the intervals in x-axis.
import random
import numpy as np
random.seed(1)
x_points = np.array(random.sample(range(1, 20), 4))
x_points.sort()
x_points = np.append(0, x_points)
x_points
[0 3 4 5 9]
I can now use the first two points and create a random linear function, but I don't know how I should continue from there to preserve the convexity. Note that a function is called convex if the line segment between any two points on the graph of the function does not lie below the graph between the two points.