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

相关推荐
Bruce_Liuxiaowei20 分钟前
Python 实例赋值遮蔽类属性:一个从不报错的静默陷阱
开发语言·python·语法糖
做运维的阿瑞28 分钟前
Python 标准库汇总:分类速览与常用模块清单
linux·运维·python
why-geo33 分钟前
Hermes Agent 与 Python 的会产生什么样的碰撞
人工智能·python·ai编程
正经教主41 分钟前
【FDE系列】阶段2:Day 29:FastAPI 进阶 — Pydantic 模型与完整 CRUD 实战
人工智能·python·fde
gCode Teacher 格码致知44 分钟前
Pandas教学-6:coerce详解
python·pandas
梦在远山后1 小时前
Electron 与 FastAPI 如何完成流式 Agent 对话
python·langchain·agent
大衛說1 小时前
12 · 文件 I/O 与序列化
python
小静AI工程实验室1 小时前
Python 爬虫中文乱码排查:严格解码、UTF-8 BOM 与 JSON 转义的 12 项实验
字符编码·爬虫·python
天天被压力1 小时前
【跨市场数据实战 #08】可转债折价机会怎么筛:3个接口抓比价、列表和实时盘口
java·人工智能·python
weixin199701080161 小时前
[特殊字符]️《从0到1搭多平台二手ERP中台:闲鱼+淘宝+京东+拼多多+Mercari统一调度》(附Python源码)
python