You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python函数test_func生成可调用的导数函数der_test_func?

问题描述

我有如下Python函数:

def test_func(x):
    return 3*x**2

希望生成它的导数函数der_test_func,要求该函数可以直接调用获取结果,例如:

>>> print(der_test_func(5))
>>> 30

也能在其他函数中正常使用,示例如下:

def func2(x):
    y = 10*der_test_func(x)
    return y

>>> print(func2(5))
>>> 300

我知道SymPy可以用来求导,但它返回的是表达式,而非可直接传入参数得到输出的函数。请问有哪些方法或变通方案可以创建der_test_func?

解决方案

方法1:手动推导导数(最直接)

对于简单的多项式函数,直接根据求导规则手动写出导数表达式,定义成函数即可:

def der_test_func(x):
    return 6*x  # 3*x²的导数是6x

# 测试
print(der_test_func(5))  # 输出30

def func2(x):
    y = 10*der_test_func(x)
    return y

print(func2(5))  # 输出300

方法2:用SymPy将表达式转换为可调用函数

SymPy的lambdify工具可以把符号表达式转换为能直接接收数值参数的Python函数,步骤如下:

import sympy as sp

# 定义符号变量
x = sp.symbols('x')
# 求导得到符号表达式
der_expr = sp.diff(3*x**2, x)
# 转换为可调用函数
der_test_func = sp.lambdify(x, der_expr)  # 若需支持numpy数组,可添加第三个参数'numpy'

# 测试
print(der_test_func(5))  # 输出30

def func2(x):
    y = 10*der_test_func(x)
    return y

print(func2(5))  # 输出300

方法3:数值求导法(适合复杂函数)

对于无法手动求导或符号求导困难的复杂函数,可以用数值差分近似计算导数,比如精度较高的中心差分法:

def der_test_func(x, h=1e-6):
    # 中心差分公式:(f(x+h) - f(x-h))/(2h)
    return (test_func(x+h) - test_func(x-h))/(2*h)

# 测试
print(der_test_func(5))  # 输出约30(浮点精度影响,结果接近30)

def func2(x):
    y = 10*der_test_func(x)
    return y

print(func2(5))  # 输出约300

这种方法是近似计算,精度由步长h控制,通常取1e-6~1e-8平衡误差与浮点稳定性。


内容的提问来源于stack exchange,提问作者NeStack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 06:50:26