Python实现分段函数求导+绘制函数曲线

代码如下:

python 复制代码
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函数来表示,才能让代码顺利运行。

相关推荐
默_笙5 天前
🍙 给每个请求过安检:FastAPI 是怎么把校验写进类型注解的
python
小羊没烦恼!5 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
qq_426003965 天前
启动playwright录制codegen生成自动化测试脚本
python·自动化
虎头金猫5 天前
4K 视频总卡在公网带宽?用 N1 + OpenList 把网盘播放链路重新理顺
运维·服务器·网络·python·容器·beautifulsoup·pandas
长沙三为智能科技5 天前
家政小程序开发从0到上线:五阶段交付流程与验收清单
python
伞伞悦读5 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
只睡四小时5 天前
Canvas 弹道联机实战:700 行 + 固定时间步长
python·websocket·html5·游戏开发·canvas
C语言小火车5 天前
C/C++ 为什么需要编译器?
开发语言·c++
奇思妙想聪明勤奋的小羊5 天前
DeepAgents第5章:子Agent 与上下文隔离—让 Agent学会委派
人工智能·python·学习·语言模型
lpfasd1235 天前
2026年第38周GitHub趋势周报
python·科技·github