数学——Euler方法求解微分方程详解(python3)
算法的數學描述圖解
實例
用Euler算法求解初值問題
\[ \frac{dy}{dx}=y+\frac{2x}{y^2}\]
初始條件\(y(0)=1\),自變量的取值范圍\(x \in [0, 2]\)
算法Python3代碼求解
# 導入包 import numpy as np import matplotlib.pyplot as plt # 定義求解函數 y_dot = y + 2*x/(y*y) def fx(y, x):return y + 2*x/(y*y) # 算法定義 def ode_euler(f, y0, tf, h):"""Solve and ODE using Euler method.Solve the ODE y_dot = f(y, t)Parameters------------:param f: functionFunction describing the ODE:param y0: array_likeInitial conditions.:param tf: floatFinal time.:param h: floatTime step:return:y : array_likeSolution to the ODE.t : array_likeTime vector."""y0 = np.array(y0)ts = np.arange(0, tf + h, h)y = np.empty((ts.size, y0.size))y[0, :] = y0for t, i in zip(ts[1:], range(ts.size - 1)):y[i + 1, :] = y[i, :] + h * f(y[i, :], t)return y, ts # 實例應用案例 def newton_cooling_example():print('Solving Newton Cooling ODE...')y, ts = ode_euler(fx, 1, 2, 0.01)print('Done.')plt.figure()plt.plot(ts, y)plt.xlabel('time [s]')plt.title('Solution to the Newton cooling equation')plt.show()代碼中的部分函數理解
numpy.array
numpy.array(object, dtype=None, copy=True, order='K', subok=False, ndmin=0)
參考numpy.array
output:創建一個array,返回類型為ndarray
實例
numpy.arange
參考numpy.arange
numpy.arange([start, ]stop, [step, ]dtype=None)
作用:在給定間隔內返回均勻間隔的值。
值在半開區間[start, stop)內生成(換句話說,包括開始但不包括終止)。返回的是ndarray而不是列表。
np.arange()函數返回一個有終點和起點的固定步長的排列,如[1,2,3,4,5],起點是1,終點是5,步長為1。
參數個數情況: np.arange()函數分為一個參數,兩個參數,三個參數三種情況 :
案例
np.arange(3,7) # array([3, 4, 5, 6]) np.arange(3,7,2) # array([3, 5])numpy.ma.size
numpy.ma.size(obj, axis=None)
參考
案例
numpy.empty
參考
numpy.empty(shape, dtype=float, order='C')
shape : int or tuple of int Shape of the empty array, e.g., (2, 3) or 2.
out : ndarray
案例
轉載于:https://www.cnblogs.com/brightyuxl/p/9990958.html
總結
以上是生活随笔為你收集整理的数学——Euler方法求解微分方程详解(python3)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 揭秘数字行为:快速地多次点击
- 下一篇: Mac上在终端上解压与压缩