python – 定义sympy函数导数的数值计算
作者:互联网
如何在sympy中定义函数导数的数值计算?
我有一些功能,我可以用函数的样条线来描述,它是使用scipy.interpolate的派生.
我想用这个函数操作一些表达式,然后用样条曲线计算表达式.
我可以使用lambdify使一个sympy函数作为样条数值进行评估.
但是,如何定义sympy函数的导数以数值方式作为样条函数进行求值?
例如.
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的数字版本.
此外,A这里可能只是一个Python函数,因为你永远不会评估它.这也更有意义,因为将函数作为参数传递给SymPy函数有点奇怪.
所有implements_function都是symfunc._imp_ = staticmethod(implementation)(这里symfunc = B,implementation = lambda r:B_spline(r)).您还需要添加fdiff,以便为B_der_spline返回一个新的SymPy函数.就像是
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
标签:spline,python,scipy,sympy 来源: https://codeday.me/bug/20191007/1864825.html