定义一个sympy函数的导数的数值求值 [英] define numerical evaluation of a derivative of a sympy function

查看:466
本文介绍了定义一个sympy函数的导数的数值求值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在sympy中定义函数导数的数值计算? 我有一些可以用样条函数描述的函数,它是使用scipy.interpolate派生的. 我想使用此功能处理一些表达式,然后使用样条线评估表达式.

How can I define the numerical evaluation of a derivative of a function in sympy? I have some functions I can describe with splines for the function and it's derivative using scipy.interpolate. I want to manipulate some expressions with this function and then evaluate the expressions with the splines.

我可以使用lambdify使sympy函数作为样条进行数字评估. 但是,如何定义sympy函数的导数以将数值作为样条线求值?

I can use lambdify to make a sympy function evaluate numerically as a spline. But how can I define the derivative of a sympy function to evaluate numerically as a spline?

例如

import sympy as sp
import numpy as np
from scipy.interpolate import InterpolatedUnivariateSpline
from sympy.ultilitis.lambdify import implemented_function, lambdify

r = sp.symbols('r')
B = sp.symbols('B', cls=sp.Function)

B_spline = InterpolatedUnivariateSpline([1,2,3,4],[1,4,9,16])
B_der_spline = InterpolatedUnivariateSpline([1,2,3,4],[2,4,6,8])
B = implemented_function(B, lambda r: B_spline(r))

class A(sp.Function):
    nargs = 2

    @classfunction
    def eval(cls, r, B):
        return r**2*B(r)

 A_eval = lambdify(r, A(r,B))
 A_eval(3)
 >>> 81.0
 A_diff_eval = lambdify(r, sp.diff(A(r,B)))
 A_diff_eval(3)
 >>> NameError: global name 'Derivative' is not defined

推荐答案

SymPy不知道如何获取样条函数的导数,因为它只有scipy的数字版本.

SymPy doesn't know how to take the derivative of the spline function, since it only has the numeric version of it from scipy.

此外,这里的A可能只是一个Python函数,因为您从未评估过它.将函数作为参数传递给SymPy函数也有点奇怪.

Also, A here could just be a Python function, since you never don't evaluate it. That also makes more sense in that passing a function as an argument to a SymPy function is a bit odd.

所有implemented_function所做的都是symfunc._imp_ = staticmethod(implementation)(此处是symfunc = Bimplementation = lambda r: B_spline(r)).您还需要添加fdiff,以便它为B_der_spline返回新的SymPy函数.像

All implemented_function does is symfunc._imp_ = staticmethod(implementation) (here symfunc = B and implementation = lambda r: B_spline(r)). You will also need to add fdiff so that it returns a new SymPy Function for B_der_spline. Something like

class B_spline_sym(Function):
    _imp_ = staticmethod(B_spline)

    def fdiff(self, argindex=1):
        return B_der_spline_sym(self.args[0])

class B_der_spline_sym(Function):
    _imp_ = staticmethod(B_der_spline)

def A(r, B):
    return r**2*B(r)

给予

In [87]: B = B_spline_sym

In [88]:  A_eval = lambdify(r, A(r,B))

In [89]:  A_eval(3)
Out[89]: 81.0

In [91]:  A_diff_eval = lambdify(r, sp.diff(A(r,B)))

In [92]:  A_diff_eval(3)
Out[92]: 108.0

这篇关于定义一个sympy函数的导数的数值求值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆