1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
import os import numpy as np import matplotlib.pyplot as plt from scipy import integrate import sympy os.chdir(r'D:\projects\wordpress\ex35') os.getcwd() def plot_direction_field(x, y_x, f_xy, x_lim=(-5, 5), y_lim=(-5, 5), ax=None): f_np = sympy.lambdify((x, y_x), f_xy, 'numpy') x_vec = np.linspace(x_lim[0], x_lim[1], 20) y_vec = np.linspace(y_lim[0], y_lim[1], 20) if ax is None: _, ax = plt.subplots(figsize=(4, 4)) dx = x_vec[1] - x_vec[0] dy = y_vec[1] - y_vec[0] for m, xx in enumerate(x_vec): for n, yy in enumerate(y_vec): Dy = f_np(xx, yy) * dx Dx = 0.8 * dx**2 / np.sqrt(dx**2 + Dy**2) Dy = 0.8 * Dy*dy / np.sqrt(dx**2 + Dy**2) ax.plot([xx - Dx/2, xx + Dx/2],[yy - Dy/2, yy + Dy/2], 'b', lw=0.5) ax.axis('tight') ax.set_title(r"$%s$" % (sympy.latex(sympy.Eq(y(x).diff(x), f_xy))), fontsize=18) return ax x = sympy.symbols("x") y = sympy.Function("y") f = y(x)**2 + x f_np = sympy.lambdify((y(x), x), f, 'math') y0 = 0 xp = np.linspace(0, 1.9, 100) xp.shape yp = integrate.odeint(f_np, y0, xp) xm = np.linspace(0, -5, 100) ym = integrate.odeint(f_np, y0, xm) fig, ax = plt.subplots(1, 1, figsize=(4, 4)) plot_direction_field(x, y(x), f, ax=ax) ax.plot(xm, ym, 'b', lw=2) ax.plot(xp, yp, 'r', lw=2) plt.savefig("example35.png", dpi=100) plt.show() plt.close() <img class=" size-full wp-image-158 aligncenter" src="https://gantovnik.com/bio-tips/wp-content/uploads/2019/01/example35.png" alt="example35" width="400" height="400" /> |
Recent Comments