Python中的多元微分

2024-06-14 12:40:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个功能

Multivariate function 我想在Python中简化和区分,定义为**

def u(x, t):
    return math.erf((x + 1) / (2 * (k * t) ** (1 / 2)))

**如果我错了,请纠正我。在

我有以下所有必要的进口货物:

^{pr2}$

以及定义符号

x, k, t = symbols('x k t')

这样做非常好:

def f(x):
     return x ** 4

diff(f(x))

返回正确答案

4x^3

然而,这

diff(u(x, t))

或者这个

diff(u(x, t), t)

返回如下错误

TypeError Traceback (most recent call last) in () ----> 1 diff(u(x, t))

in u(x, t) 1 def u(x, t): ----> 2 return math.erf((x + 1) / (2 * (k * t) ** (1 / 2)))

C:\Anaconda\lib\site-packages\sympy\core\expr.py in float(self) 223 if result.is_number and result.as_real_imag()1: 224 raise TypeError("can't convert complex to float") --> 225 raise TypeError("can't convert expression to float") 226 227 def complex(self):

TypeError: can't convert expression to float

在Matlab中,我可以轻松做到:

syms x;
syms k;
syms t;
u = erf((x + 1)/(2 * sqrt(k * t)));
LHS = simplify(diff(u, t))
RHS = k * simplify(diff(u, x, 2))

我的问题是,如何区分和/或简化Python中多个变量的数学函数?在


Tags: toinselfconvertreturn定义defdiff
2条回答

您需要使用sympy.erf,而不是math.erf

>>> import sympy
>>> x, k, t = sympy.symbols('x k t')
>>> def u(x, t):
...     return sympy.erf((x + 1) / (2 * (k * t) ** (1 / 2)))
>>> sympy.diff(u(x, t), x, t)
(0.25*(k*t)**(-1.5)*(x + 1)**2 - 0.5*(k*t)**(-0.5))*exp(-(k*t)**(-1.0)*(x + 1)**2/4)/(sqrt(pi)*t)

像这样使用sympy

>>> from sympy import symbols, diff
>>> x, y = symbols('x y', real=True)
>>> diff( x**2 + y**3, y)
3*y**2
>>> diff( x**2 + y**3, y).subs({x:3, y:1})
3

你必须指定要区分的变量。在

相关问题 更多 >