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

相关推荐
曲幽13 小时前
数据库实战:FastAPI + SQLAlchemy 2.0 + Alembic 从零搭建,踩坑实录
python·fastapi·web·sqlalchemy·db·asyncio·alembic
用户83562907805118 小时前
Python 实现 PowerPoint 形状动画设置
后端·python
ponponon19 小时前
时代的眼泪,nameko 和 eventlet 停止维护后的项目自救,升级和替代之路
python
Flittly19 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(5)Skills (技能加载)
python·agent
敏编程20 小时前
一天一个Python库:pyarrow - 大规模数据处理的利器
python
Flittly21 小时前
【从零手写 ClaudeCode:learn-claude-code 项目实战笔记】(4)Subagents (子智能体)
python·agent
明月_清风1 天前
Python 装饰器前传:如果不懂“闭包”,你只是在复刻代码
后端·python
明月_清风1 天前
打破“死亡环联”:深挖 Python 分代回收与垃圾回收(GC)机制
后端·python
ZhengEnCi2 天前
08c. 检索算法与策略-混合检索
后端·python·算法
明月_清风2 天前
Python 内存手术刀:sys.getrefcount 与引用计数的生死时速
后端·python