具體如下:
如上圖所示的分段函數如何在Python中繪製出來?
import matplotlib.pyplot as plt import numpy as np def f(x): if x <= -1: return -0.5 - x if -1 < x <= 1: return 0.5 * (x ** 2) else: return x - 0.5 x = np.linspace(-3, 3) y = [] for i in x: y_1 = f(i) y.append(y_1) plt.plot(x, y) plt.grid() plt.show()
我們換個範例:
import matplotlib.pyplot as plt import numpy as np def f(x): if x <= -1: return 1 if -1 < x <= 1: return 0.5 * (x ** 2) else: return 1 x = np.linspace(-3, 3) y = [] for i in x: y_1 = f(i) y.append(y_1) y_2 = x ** 2 plt.plot(x, y) plt.grid() plt.show()
結果展示為:
以上是怎麼使用Python繪製分段函數的詳細內容。更多資訊請關注PHP中文網其他相關文章!