[关闭]
@MitoY 2016-04-06T01:57:26.000000Z 字数 1057 阅读 675

第四、五次作业


作业题目分析

第一章的练习题,皆为数值求解常微分方程。因此我写了一个通用的求显式常微分方程数值解的程序。


程序说明

程序在这里

1. 解常微分方程

首先需要手动输入常微分方程。譬如对方程 ,写入

  1. def deriv(x, y):
  2. return -x * y

然后使用求解函数 f(), 输入方程deriv,初始值init = (x0, y0),末值x1;可以选择输入函数值的区间y_range,每两点间的迭代数step,点的数目point,如果不输入则取默认值。例如:

  1. f(deriv)

or

  1. f(deriv, init = (0, 0), x1 = 10, y_range = (-100, 100), step = 1, point = 1000)

函数的返回值为从x = init[0]x = x1的一组点,点的数目为point+1,点的格式为list, 每个item形式为[x, y, deriv(x, y)]。可以写f(deriv)[-1]即得到末态点[x1, y1, deriv(x1, y1)]

2. 绘制图像

给定函数deriv,初始值,末值,可以直接绘制图像。

  1. import matplotlib.pyplot as plt
  2. plt.plot(*trans(f(deriv, init = (-3, 0.01), x1 = 3)))
  3. plt.show()

要想绘制函数在一定范围内的多条图像(类似stream plot),可使用draw_1draw_2函数。

  1. import matplotlib.pyplot as plt
  2. draw_1(deriv, x_range = (-3, 3), y_range = (-3, 3), density = 8)
  3. draw_2(deriv, x_range = (-3, 3), y_range = (-3, 3), density = 16)
  4. plt.show()

两种函数绘图风格各有不同,请自行研究啦^_^


实例

1. 求解常微分方程

  1. def deriv(t, v):
  2. return 10 - v
  3. print f(deriv, (0, 0), 2)[-1]

得到 t = 2v = 8.646645360453359

2. 绘出图像

  1. import matplotlib.pyplot as plt
  2. plt.plot(*trans(f(deriv, init = (0, 0), x1 = 6)))
  3. plt.show()

enter image description here

3. 更多绘图


enter image description here


添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注