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

相关推荐
FishCoderh1 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅1 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽3 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时6 小时前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿8 小时前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780511 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng81 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi1 天前
Chapter 2 - Python中的变量和简单的数据类型
python
JordanHaidee1 天前
Python 中 `if x:` 到底在判断什么?
后端·python
ServBay1 天前
10分钟彻底终结冗长代码,Python f-string 让你重获编程自由
后端·python