微分方程的計算

例如,我們要解以下微分方程:

\displaystyle \frac{dx}{dt}=kx

 In [1]: from sympy import *
 
 In [2]: from sympy.abc import x, t, k

 In [3]: x = Function('x')

 In [4]: dsolve(Eq(Derivative(x(t), t) - k * x(t), 0), x(t))
 Out[4]:
 \displaystyle x(t) = C_{1} e^{k t}

我們也可以設定初始條件,例如,在上例中,t = 0 時,x(0) = 0.5。這樣就可以求得常數。

 In [8]: dsolve(Eq(Derivative(x(t), t) - k * x(t), 0), x(t), ics = {x(0): 0.5})
 Out[9]:
 \displaystyle x(t) = 0.5 e^{k t}

參考閱讀:
https://docs.sympy.org/latest/modules/solvers/ode.html

單變數微積分的計算

在 Python 的 SymPy 計算微積分,可以用以下方法。首先,匯入需要的套件。

 In [1]: from sympy import diff, integrate
 
 In [2]: from sympy.abc import x, y, z

 In [3]: from sympy import init_printing

 In [4]: init_printing()

用以下函數計算微分:

 In [5]: diff(x ** 2 - 3 * x + 8, x)
 Out[5]: 
 \displaystyle 2 x - 3

 In [9]: diff(x ** 2 - 3 * x + 8, x).subs(x, 4)
 Out[9]: 5
 # 上式是求 x = 4 時的微分值

用以下函數計算積分:

 In [8]: integrate(x ** 2 - 3 * x + 5, x)
 Out[8]:
 \displaystyle \frac{x^{3}}{3} - \frac{3 x^{2}}{2} + 5 x

 In [9]: integrate(x ** 2 - 3 * x + 5, (x, -1, 4))
 Out[9]: 145/6
 # 上式是求 x 從 -1 到 4 的積分值。

 In [14]: integrate(x ** 2 - 3 * x + 5, (x, -1, 4)).evalf()
 Out[14]: 24.1666666666667
 # 上式是將積分值以小數表示

 

參考閱讀:
https://docs.sympy.org/latest/tutorial/calculus.html