本文主要介绍了Python绘制分段函数,具体如下:

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()

Python绘制分段函数的实现示例

我们换个例子:

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绘制分段函数的实现示例

原文地址:https://blog.csdn.net/wzk4869/article/details/127892398

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-08
  • 2021-10-19
  • 2022-12-23
  • 2022-12-23
  • 2023-03-10
猜你喜欢
  • 2021-10-09
  • 2022-12-23
  • 2023-04-10
  • 2022-12-23
  • 2021-06-15
  • 2022-12-23
  • 2021-10-09
相关资源
相似解决方案