I was trying to plot a function with absolute values and it's piecewise counterpart, but matplotlib was ploting the function with jagged corners.
Here is my full code:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use("dark_background")
def f(x):
return abs(2 * x - 3) + abs(3 * x + 1) - abs(5 * x - 3)
def g(x):
if x < -1/3:
return -1
if -1/3 < x < 3/5:
return 6 * x + 1
if 3/5 < x < 3/2:
return -4 * x + 7
if x > 3/2:
return 1
gf = np.vectorize(g)
x = np.linspace(-1, 2, 300)
plt.figure(figsize = (10, 4))
plt.subplot(1, 2, 1)
plt.plot(x, f(x), color = "blue")
plt.subplot(1, 2, 2)
plt.plot(x, gf(x), color = "red")
plt.show()
And here is the plot that was generated: Plot of the functions
The solution to this problem I've found was to add a small of x to the constant output:
def g(x):
if x < -1/3:
return -1 + 0.000001 * x
if -1/3 < x < 3/5:
return 6 * x + 1
if 3/5 < x < 3/2:
return -4 * x + 7
if x > 3/2:
return 1 + 0.000001 * x
This solved my problem, but I still don't know why it works, or what's wrong with the first plot I've made.
Fixed jagged plot of piecewise function
If anyone knows a simpler solution or the source of the problem, let me know.