在Python中編寫分段函數的方法
Python代碼如下:
import numpy as np
import matplotlib.pyplot as plt
#繪制分段函數
def sgn(x):
if x > 0:
return 1
elif x < 0:
return -1
else:
return 0
t = np.arange(0, 1, 0.01)
y = []
for i in t:
y_1 = 4 * np.sin(4 * np.pi * i) - sgn(i - 0.3) - sgn(0.72 - i)
y.append(y_1)
plt.plot(t, y)
plt.xlabel("t")
plt.ylabel("y")
plt.title("Heavsine")
plt.show()