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

沒有留言:

張貼留言

Samsung A16 移除雲端 app

Samsung A16 手機很不識相, 一直頻煩要使用者登錄三星的雲端,  上 google 查了一下, 只要移除 scloud app 就解決, 但必須要在開發者模式, 試了一下, 結果 usb port 又無法連線. 只好在 linux 底下用一些終端機命令, 在 Wifi ...