2025年3月7日 星期五

使用 python3 的 autograd package 產生 n-階微分方程式並繪圖

1. 先安裝 python3 的 python3-venv 虛擬環境, 並安裝到目錄
    sudo apt install python3-venv
    cd ~
    python3 -m venv venv
2. 進入 python3 虛擬環境, 安裝 autograd
    cd ~
    source venv/bin/activate
    pip install autograd
3. 編輯以下測試檔:   xed ~/test_grad.py
from autograd import elementwise_grad as egrad
import autograd.numpy as audo_np
import matplotlib.pyplot as plt
tanh = lambda t: (1.0 - audo_np.exp((-2 * t))) / (1.0 + audo_np.exp(-(2 * t)))
derivative_ = lambda n, f: derivative_(n - 1, derivative_(1, f)) if n > 1 else egrad(f) # dⁿf(x)/dx
#
x = audo_np.linspace(-7, 7, 500)
y0 = tanh(x)
y1 = derivative_(1, tanh)(x)
y2 = derivative_(2, tanh)(x)
y3 = derivative_(3, tanh)(x)
y4 = derivative_(4, tanh)(x)
#
plt.plot(x, y0, x, y1,  x, y2, x, y3, x, y4)
plt.show()

4. 啟用虛擬環境, 執行看看:
    cd ~
    source venv/bin/activate
    python3 test_grad.py

p.s.如果不想安裝 autograd, 可以上官網把整個目錄下載回來:  https://github.com/HIPS/autograd

沒有留言:

張貼留言

用泰勒展開式逼近一個 sin 函數

用 python3 的 autograd 模組來驗證: from autograd import elementwise_grad as grad import autograd.numpy as audo_np import matplotlib.pyplot as plt _...