顯示具有 Mathematics 標籤的文章。 顯示所有文章
顯示具有 Mathematics 標籤的文章。 顯示所有文章

2020年4月8日 星期三

Python 學習筆記 : 安裝 SymPy 套件

昨天二哥傳了一個解微分方程式的 Python 程式給我, 說是在網路上找到的, 但在 Anaconda 下無法執行, 要我看看哪裡有問題. 我開啟原始檔發現裡面用到 Sympy, 這是 Python 用來繪製數學公式與進行符號運算的套件, 所以我就先安裝此套件來跑跑看.

Sympy 套件其實不大, 大約 5.6MB 而已, 直接用 pip 安裝即可 :

E:\>pip3 install sympy   
Collecting sympy
  Downloading sympy-1.5.1-py2.py3-none-any.whl (5.6 MB)
Collecting mpmath>=0.19
  Downloading mpmath-1.1.0.tar.gz (512 kB)
Installing collected packages: mpmath, sympy
    Running setup.py install for mpmath ... done
Successfully installed mpmath-1.1.0 sympy-1.5.1

可見除了 Sympy 本身外還安裝了一個相依模組 mpmath.

但這個名為 D.E.Calculator.py 的 Python 程式卻因為裡面有一個不明的 display() 函數而執行失敗, 原因是 "is not defined" :

E:\>python D.E.Calculator.py 
Differential equation example one: Separable Equation
Traceback (most recent call last):
  File "D.E.Calculator.py", line 30, in <module>
    display(diffeq)
NameError: name 'display' is not defined

D.E.Calculator.py 原始碼如下 :

#======================================================
from __future__ import division #It must be at the begining.
from sympy import * #This imports all the functions and classes from SymPy.
x, y, z, t, C1 = symbols('x y z t C1')
k, m, n = symbols('k m n', integer = True)
f, g, h, O = symbols('f g h O', cls = Function)
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
The above five rows are automatically executed once you clicked the check
box of "Use symbolic math." But if you do not check the box, remember to type
these commands to make it work in the way you expect. More information could
be found here: http://blog.csdn.net/u012675539/article/details/46981305
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""

# -*- coding: utf-8 -*-
"""
Created on Tue Jan 30 09:59:38 2018
@author: ShihHsing Chen
"""
import sympy
import matplotlib.pyplot as plt
import time #I just want to know how much time does a run would take.
start = time.time()

#"Color" should be titlized, and backcolor is also available. This function
#is quite useful as you work under a dark theme. It would give you a clear
#view of your "display()."
init_printing(use_latex = True, forecolor = "Green")

print("Differential equation example one: Separable Equation")
diffeq = Eq(f(x).diff(x), f(x)/(1+x))
display(diffeq)
print("Solution:")
gen_sol = dsolve(diffeq, f(x))
display(gen_sol)
#plot = gen_sol.rhs.subs(C1, 1)
#plot(plot, (x, -100, 100), title = "Solution with C1 = 1", autoscale= True)

end = time.time()
elapsed = end - start
print("Time taken: ", elapsed, "seconds.")
#=========================================================

我用 dir() 查詢 Sympy 的成員, 並未找到此方法, 所以我覺得這個程式應該不完整, display() 可能是一個自訂函數. 所附的 Word 說明文件有提到要下載安裝 WinPython 才能執行此程式, 但我搜尋 WinPython 卻沒有找到它有 display() 函數的資訊, 且二哥用 Anaconda 這樣包山包海的 Python 軟體都無法執行了, 實在不想再去安裝 WinPython 來跑看看. 不過作者提到他的部落格 "FANATIC FRANKY", 我去看了一下, 應該是一位留美的學霸, 他寫的一些 Python 相關文章很不錯, 值得參考 :

# https://steve61022002.blogspot.com/search?q=python

OK, 這個微分方程式的程式就擱著吧, 反正我遲早會自己去寫.

倒是既然安裝了 Sympy, 那就來學學怎麼用唄.

Sympy 是 Ondřej Čertík 和 Aaron Meurer 等人於 2003 年釋出的開源符號計算套件, 全部使用 Python 撰寫而不依賴外部函式庫, 常用於解微積分, 微分方程式等數學計算, 參考 :

# https://zh.wikipedia.org/wiki/SymPy

教學文件參考 :

# https://docs.sympy.org/latest/tutorial/

下面這篇文章寫得非常棒, 值得細讀 :

# SymPy:使用 Python 幫你導煩人的數學公式

科學計算分為數值計算 (numeric computation) 與符號計算 (symbolic computation), 符號計算又稱為計算機代數 (computer algebra), 它是不允許捨入誤差的精確計算, 而我們常用的數值計算則是有捨入誤差的近似運算, 結果並不是精確的.

同樣都是使用電腦進行科學運算, 但與數值計算不同的是, 符號計算用來推導數學公式, 例如對運算式進行因式分解, 演算微分與積分結果, 或者是解微分方程式等等, 參考 :

# 符号计算有什么用?

但 Sympy 第一次吸引我注意的其實是它可以顯示出漂亮的數學公式, 下面就照教學文件資料來顯示 (1/x)^(1/2) 的積分運算式吧 :

# https://docs.sympy.org/latest/tutorial/printing.html


>>> from sympy import *
>>> x,y,z=symbols('x y z')
>>> init_printing()
>>> Integral(sqrt(1/x),x)
⌠
⎮     ___
⎮    ╱ 1
⎮   ╱  ─  dx
⎮ ╲╱   x
⌡

嗯, 沒有想像中的漂亮, 因為這是 Command Line 環境啊! 若要達到預期效果, 可能要在 Jupyter Notebook 的網頁環境中才行, 這樣才能藉助 LATEXT 的描繪能力顯示完美的數學符號.

可用 Jupyter Notebook 官網所提供的線上版來測試 Sympy, 網址如下 :

# https://hub.gke.mybinder.org/user/jupyterlab-jupyterlab-demo-a78xdule/lab


首先在 Launcher 中點選 "Python 3" 按鈕啟動 Python 3 的 Notebook :




依序輸入上面的程式, 每輸入一行要按上面的 Play 鍵, 就會出現下一個輸入列, 最後就會顯示完美的積分符號 :




2018年11月20日 星期二

幾本工程數學好書

這幾天在 Amazon 找到幾本工程數學的好書, 紀錄如下 :

# Advanced Modern Engineering Mathematics 5th ed. (2018, Glyn James)




此書特點是以 Matlab 與 Maple 作為計算工具, 含有大量例題與習題. 其次它是從矩陣線性代數講起, 而不是一般從微分方程式開始. 計算範例如果是用 Python 那就更棒了, 不過我也可以一邊看一邊將 Matlab 改寫為 Python 版, 或許這也是磨練 Python 技能的好方法.


# Advanced Engineering Mathematics 6th ed. (2018, Dennis G. Zill)




這本是很標準的工數教科書, 第一章就是從微分方程講起. 此書開頭還附上微積分公式表, 對於常忘記公式的人很方便, 不需要再去翻查微積分的書.


# Advanced Engineering Mathematics 7th ed. (2012, Peter O'Neil)




這本書雖然是 2012 年的書了, 但編輯俐落, 非常適合自學, 我蠻喜歡此書的風格. 


# Engineering Mathematics 8th ed (2017, John Bird)



此書不像一般工程數學那麼難, 反而像是高中數學, 適合作為正式學習工程數學的暖身書.