数学——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)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 揭秘数字行为:快速地多次点击
- 下一篇: Python的scrapy之爬取顶点小说