代码如下:
import sympy as sp
import numpy as np
import matplotlib.pyplot as plt
from sympy.utilities.lambdify import lambdify# 定义符号变量
x = sp.symbols('x')
# expr = sp.Piecewise((0,0< x <= 5), (1, x > 5))
# 定义分段原函数
#---------------------------------下面是原函数和绘图区间定义-----------------------------------------------------
piecewise_function = sp.Piecewise((x**2, x < 0),(2*x + 1, sp.And(x>=0 , x<1)),(-x + 2, x >= 1))
left=-5
right=3
x_values = np.linspace(left, right, 1000)
#--------------------------------------------------------------------------------------
def derivative_values(piecewise_function):# 计算分段函数的导数derivative_piecewise = sp.diff(piecewise_function, x) # 打印导数表达式print(derivative_piecewise)# 将导数表达式转换为lambda函数以方便数值计算derivative_func = lambdify(x, derivative_piecewise, 'numpy')# 创建x值向量并计算导数值derivative_values = derivative_func(x_values)return derivative_values#-----------------------------------------绘制图像定义--------------------------------
plt.figure(figsize=(8, 6))
plt.plot(x_values, derivative_values(piecewise_function), label='Derivative of Piecewise Function', lw=2)
plt.xlabel('x')
plt.ylabel('dy/dx')
plt.legend()
plt.grid(True)
plt.show()
上述代码中注意,(2*x + 1, sp.And(x>=0 , x<1)),
整理表示的是在0≤x<1的区间中,要使用sympy.And函数来表示,才能让代码顺利运行。