# 4.4 常微分方程

sympy提供了sympy.ode.dsolve()函数用来求解常微分方程。

dsolve()函数的用法如下：

```python
sympy.solvers.ode.**dsolve**(*eq*, *func=None*, *hint='default'*,
*simplify=True*, *ics=None*, *xi=None*, *eta=None*, *x0=0*, *n=6*,
*kwargs*)
```

其中, eq可以使任意支持的常微分方程，它可也是一个等式，也可以是一个表达式。当eq是一个表达式时，假设它等于0。

func为一个变量的函数，其在该变量中的导数构成常微分方程eq。它将被自动检测(如果无法检测，则会引发一个错误)。

hint是您希望dsolve使用的求解方法。使用classify\_ode(eq, f(x))获取ODE的所有可能提示。默认提示default将使用classify\_ode()首先返回的任何提示。

simplify通过odesimp()实现简化。有关更多信息，请参见它的文档字符串。例如，关闭此选项可禁用对func的求解或任意常数的简化。它仍然会与这个提示相结合。注意，如果启用此选项，解决方案可能包含比ODE的顺序更多的任意常数。

xi和eta是常微分方程的无穷小函数。它们是微分方程不变的点变换李群的无穷小。用户可以为无穷小指定值。如果没有指定任何值，则使用infinitesimals()在各种启发式的帮助下计算xi和eta。

ics是微分方程的一组初始/边界条件。它应该以{f(x0): x1, f(x).diff(x)的形式给出。subs(x, x2): x3}等等。对于幂级数溶液，如果没有指定初始条件，则假定f(0)为C0，幂级数解的计算值为0左右。

x0是求微分方程幂级数解的点。

n给出因变量的指数，在此之前，微分方程的幂级数解将被求值。

下面让我们通过两个例子来对常微分方程的求解方法进行讲解.

## 4.4.1 常微分方程的通解

例：求$$y' + xy = 0$$的通解。

在本例中，直接在dsolve()函数中传入待求常微分方程以及希望求解的函数，即可求得该常微分方程的通解。

```python
[]:y=Function('y')

dsolve(Eq(diff(y(x),x)+x\*y(x)), y(x))
```

\[]:![](/files/5IAHDms1ekGP7KJbz6IM)

## 4.4.2 常微分方程的特解

例：求方程$$y'' + 2y' + 3y = 0$$满足初始条件$$y(0)=0, y'(0) = 1$$的全部解。

在本例中，我们使用前面所述的方法求得该常微分方程的通解：

```python
[]:dsolve(Eq(y(x).diff(x,x)+2\*y(x).diff(x)+3\*y(x)), func=y(x))
```

\[]: ![](/files/dexFdNGbL9Gh0TGj5Mkx)

为了求得该方程在初始条件下$$y(0)=0, y'(0)=1$$的特解，需要额外指定两个超参数：ics，以及n。其中ics以集合的形式接收常微分方程的初始条件，n为因变量的指数。在本例中，ics={y(0): 0, y(x).diff(x).subs(x, 0): 1}, n=2。

```python
[]:dsolve(Eq(y(x).diff(x,x)+2\*y(x).diff(x)+3\*y(x)), func=y(x),

ics={y(0): 0, y(x).diff(x).subs(x, 0): 1}, n=2)
```

\[]: ![](/files/r25NGpKR5meQCWIRPgRq)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://johannesliu.gitbook.io/learning-advanced-mathematics-with-python/4.0-calculus/4.4-ordinary_differential_equations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
