單變數微積分的計算

在 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