def test_one_step(): """ Проверяем методы Эйлера и Рунге-Кутты """ y0 = np.array([0., 1.]) t0 = 0 t1 = np.pi ode = Harmonic(y0, 1, 1) for dt in [0.1, 0.01]: ts = np.arange(t0, t1 + dt, dt) exact = ode[ts].T fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(8, 4)) ax1.plot(ts, [e[0] for e in exact], 'k', label='Exact') colors = 'rgbcmyk' for i, method in enumerate([ ExplicitEulerMethod(), ImplicitEulerMethod(), RungeKuttaMethod(collection.rk4_coeffs), RungeKuttaMethod(collection.dopri_coeffs), ]): ode.clear_call_counter() _, y = fix_step_integration(method, ode, y0, ts) n_calls = ode.get_call_counter() print( f'One-step {method.name}: {len(y)-1} steps, {n_calls} function calls' ) ax1.plot(ts, [_y[0] for _y in y], f'{colors[i]}.--', label=method.name) ax2.plot(ts, get_accuracy(exact, y), f'{colors[i]}.--', label=method.name) ax1.legend(), ax1.set_title('y(t)') ax2.legend(), ax2.set_title('accuracy') fig.suptitle(f'test_one_step, dt={dt}') fig.tight_layout() plt.show()
def test_one_step(): """ test Euler and RK methods """ y0 = np.array([0., 1.]) t0 = 0 t1 = np.pi / 2 dt = 0.1 f = Harmonic(y0, 1, 1) ts = np.arange(t0, t1 + dt, dt) exact = f[ts].T _, (ax1, ax2) = plt.subplots(1, 2) ax1.plot(ts, [e[0] for e in exact], 'k', label='Exact') colors = 'rgbcmyk' for i, method in enumerate([ ExplicitEulerMethod(), ImplicitEulerMethod(), RungeKuttaMethod(collection.rk4_coeffs), RungeKuttaMethod(collection.dopri_coeffs), ]): f.clear_call_counter() _, y = fix_step_integration(method, f, y0, ts) n_calls = f.get_call_counter() print( f'One-step {method.name}: {len(y)-1} steps, {n_calls} function calls' ) ax1.plot(ts, [_y[0] for _y in y], f'{colors[i]}.--', label=method.name) ax2.plot(ts, get_accuracy(exact, y), f'{colors[i]}.--', label=method.name) ax1.set_xlabel('t'), ax1.set_ylabel('y'), ax1.legend() ax2.set_xlabel('t'), ax2.set_ylabel('accuracy'), ax2.legend() plt.suptitle('test_one_step') plt.show()
def test_one_step(): """ test Euler and RK methods """ y0 = np.array([0., 1.]) t0 = 0 t1 = np.pi / 2 dt = 0.1 f = Harmonic(y0, 1, 1) ts = np.arange(t0, t1 + dt, dt) exact = f[ts].T plt.figure() plt.subplot(1, 2, 1) plt.plot(ts, [e[0] for e in exact], 'k', label='Exact') colors = 'rgbcmyk' for i, method in enumerate([ ExplicitEulerMethod(), ImplicitEulerMethod(), RungeKuttaMethod(collection.rk4_coeffs), RungeKuttaMethod(collection.dopri_coeffs), ]): _, y = fix_step_integration(method, f, y0, ts) print(f'len(Y): {len(y)}') print(f'Function calls: {f.get_call_counter()}') plt.subplot(1, 2, 1), plt.plot(ts, [_y[0] for _y in y], f'{colors[i]}.--', label=method.name) plt.subplot(1, 2, 2), plt.plot(ts, get_log_error(exact, y), f'{colors[i]}.--', label=method.name) plt.subplot(1, 2, 1), plt.xlabel('t'), plt.ylabel('y'), plt.legend() plt.subplot(1, 2, 2), plt.xlabel('t'), plt.ylabel('accuracy'), plt.legend() plt.suptitle('test_one_step') plt.show()