Python偏导数

时间:2018-09-29 10:38:38

标签: python-3.x sympy derivative

我正在尝试将数字放入具有偏导数的函数中,但是我找不到正确的方法来做,我已经搜索了所有互联网,但总是遇到错误。这里是代码:

from sympy import symbols,diff
import sympy as sp
import numpy as np
from scipy.misc import derivative
a, b, c, d, e, g, h, x= symbols('a b c d e g h x', real=True)
da=0.1
db=0.2
dc=0.05
dd=0
de=0
dg=0
dh=0
f = 4*a*b+a*sp.sin(c)+a**3+c**8*b
x = sp.sqrt(pow(diff(f, a)*da, 2)+pow(diff(f, b)*db, 2)+pow(diff(f, c)*dc, 2))
def F(a, b, c):
return x

print(derivative(F(2 ,3 ,5)))

我收到以下错误:派生()缺少1个必需的位置参数:'x0'

我是python的新手,所以也许这是一个愚蠢的问题,但是如果有人帮助我,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

您可以在点foo处通过变量abc找到函数(2,3,5)的三个偏导数:

f = 4*a*b+a*sp.sin(c)+a**3+c**8*b
foo = sp.sqrt(pow(diff(f, a)*da, 2)+pow(diff(f, b)*db, 2)+pow(diff(f, c)*dc, 2))

foo_da = diff(foo, a)
foo_db = diff(foo, b)
foo_dc = diff(foo, c)

print(foo_da," = ", float(foo_da.subs({a:2, b:3, c:5})))
print(foo_db," = ", float(foo_db.subs({a:2, b:3, c:5})))
print(foo_dc," = ", float(foo_dc.subs({a:2, b:3, c:5})))

答案 1 :(得分:0)

我使用了python包'sympy'来执行偏导数。要评估偏导数的点是val。参数“ val”可以作为列表或元组传递。

# Sympy implementation to return the derivative of a function in x,y
# Enter ginput as a string expression in x and y and val as 1x2 array

def partial_derivative_x_y(ginput,der_var,val):
    import sympy as sp
    x,y = sp.symbols('x y')
    function = lambda x,y: ginput
    derivative_x = sp.lambdify((x,y),sp.diff(function(x,y),x))
    derivative_y = sp.lambdify((x,y),sp.diff(function(x,y),y))
    if der_var == 'x' :
        return derivative_x(val[0],val[1])
    if der_var == 'y' :
        return derivative_y(val[0],val[1])

 input1 = 'x*y**2 + 5*log(x*y +x**7) + 99'
 partial_derivative_x_y(input1,'y',(3,1))