本文主要介绍了Python绘制分段函数,具体如下:
如上图所示的分段函数如何在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绘制分段函数的实现示例的文章就介绍到这了,更多相关Python绘制分段函数内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!