|
|
@@ -225,7 +225,7 @@
|
|
|
" x = x0\n",
|
|
|
" xs = [x]\n",
|
|
|
" for i in range(1, max_steps):\n",
|
|
|
- " x = x + f(x, t0 + h*(i-1))*h\n",
|
|
|
+ " x = x + f(x)*h\n",
|
|
|
" xs.append(x)\n",
|
|
|
" return xs\n",
|
|
|
"\n",
|
|
|
@@ -238,7 +238,7 @@
|
|
|
"x0 = np.matrix([[1.0],[0.0]]) \n",
|
|
|
"\n",
|
|
|
"# Simulation\n",
|
|
|
- "xs_e = Explicit_Euler().simulate(lambda x,t: A_num*x, x0, 0.0, h, num_steps)\n",
|
|
|
+ "xs_e = Explicit_Euler().simulate(lambda x: A_num*x, x0, 0.0, h, num_steps)\n",
|
|
|
"\n",
|
|
|
"# Plotting\n",
|
|
|
"plt.figure(1)\n",
|
|
|
@@ -318,6 +318,52 @@
|
|
|
"\n",
|
|
|
"plt.show()"
|
|
|
]
|
|
|
+ },
|
|
|
+ {
|
|
|
+ "cell_type": "markdown",
|
|
|
+ "metadata": {},
|
|
|
+ "source": [
|
|
|
+ "## Exercise: Implement the Midpoint Method"
|
|
|
+ ]
|
|
|
+ },
|
|
|
+ {
|
|
|
+ "cell_type": "markdown",
|
|
|
+ "metadata": {},
|
|
|
+ "source": [
|
|
|
+ "Adapt the midpoint method introduced in the Example1_CruiseController notebook to work with the mass spring damper vector IVP."
|
|
|
+ ]
|
|
|
+ },
|
|
|
+ {
|
|
|
+ "cell_type": "code",
|
|
|
+ "execution_count": null,
|
|
|
+ "metadata": {},
|
|
|
+ "outputs": [],
|
|
|
+ "source": [
|
|
|
+ "class Midpoint:\n",
|
|
|
+ " def simulate(self, f, x0, t0, h, max_steps):\n",
|
|
|
+ " x = x0\n",
|
|
|
+ " xs = [x]\n",
|
|
|
+ " for i in range(1, max_steps):\n",
|
|
|
+ " # TODO: implement the following \n",
|
|
|
+ " x = ...\n",
|
|
|
+ " xs.append(x)\n",
|
|
|
+ " return xs\n",
|
|
|
+ "\n",
|
|
|
+ "# Run solver and plot\n",
|
|
|
+ "xs_mid = Midpoint().simulate(lambda x: A_num*x, x0, 0.0, h, num_steps)\n",
|
|
|
+ "\n",
|
|
|
+ "# Plotting\n",
|
|
|
+ "plt.figure(1)\n",
|
|
|
+ "plt.plot(t_range,[x[0,0] for x in xs_e], 'o', markersize=3, label='x_euler')\n",
|
|
|
+ "plt.plot(t_range,[x[0,0] for x in xs_mid], 'o', markersize=3, label='x_midpoint')\n",
|
|
|
+ "plt.plot(t_range,[x[0,0] for x in xs_sol], '-', markersize=3, label='x_solution')\n",
|
|
|
+ "plt.xlabel('t (s)')\n",
|
|
|
+ "plt.ylabel('position (m)')\n",
|
|
|
+ "\n",
|
|
|
+ "plt.legend()\n",
|
|
|
+ "\n",
|
|
|
+ "plt.show()"
|
|
|
+ ]
|
|
|
}
|
|
|
],
|
|
|
"metadata": {
|