Write a Python program to implement the Runge-Kutta Method of order 4 to approxi
ID: 3828875 • Letter: W
Question
Write a Python program to implement the Runge-Kutta Method of order 4 to approximate the value of the solution of the differential equation x'(t) = f(t, x) x(a) = xa at t = b using n steps. The definition statement of your program should be def RK4 (f, a, b, xa, n) Your output statement should be of the form: The approximate value of the solution at x = bbb is SSSS. where bbb is the value b and SSSS is the solution value. Test your program on the example at the bottom of page 315. Consider the differential equation x' = (2 - t)x with x(2) = 1. Use your Runge-Kutta code to approximate the solution at t = 3 with the following step sizes: t = 2^-k for k = 0.1, ..., 6. The exact solution is x(t) = e^-(1/2) (t - 2)^2 Compute the error in each approximation and the ratio of the errors with the previous value of t (for example error(t = 2^-1)/error (t = 2^-0), error (t = 2^-2)/error (t = 2^-1)). Explain what the ratios tell you about the order of the method.Explanation / Answer
===using lambda Runge Kutta code ===
<lang Python>def RK4(f):
return lambda t, y, dt: (
lambda dy1: (
lambda dy2: (
lambda dy3: (
lambda dy4: (dy1 + 2*dy2 + 2*dy3 + dy4)/6
)( dt * f( t + dt , y + dy3 ) )
)( dt * f( t + dt/2, y + dy2/2 ) )
)( dt * f( t + dt/2, y + dy1/2 ) )
)( dt * f( t , y ) )
def theory(t): return (t**2 + 4)**2 /16
from math import sqrt
dy = RK4(lambda t, y: t*sqrt(y))
t, y, dt = 0., 1., .1
while t <= 10:
if abs(round(t) - t) < 1e-5:
print("y(%2.1f) = %4.6f error: %4.6g" % ( t, y, abs(y - theory(t))))
t, y = t + dt, y + dy( t, y, dt )
</lang>
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.