In: Computer Science
Design and construct a computer program in one of the approved
languages (C, C++, C#, Java, Pascal, Python, etc.) that will
illustrate the use of a fourth-order
explicit Runge-Kutta method of your own design. In other words, you
will first have to solve the Runge-Kutta equations of condition for
the coefficients
of a fourth-order Runge-Kutta method.
Then, you will use these coefficients in a computer program to
solve the ordinary differential equation below.
Be sure to follow the documentation and programming style policies
of the Computer Science Department.
The initial value problem to be solved is the following:
x'(t) = 3 x2 cos(5 t)
subject to the initial condition: x(0) = 1.0
Obtain a numerical solution to this problem over the range from t=0.0 to t=2.0
for seven different values of the stepsize,
h=0.1, 0.05 , 0.025 , 0.0125 , 0.00625 , 0.003125 , and 0.0015625 .
In other words, make seven runs with 20, 40, 80, 160, 320, 640,
and 1280 steps, respectively.
For each run, print out the value of h, then a table of t and x,
and then the error at t=2. You may use the following
very precise value for your "true answer" in order to compute the
error at t=2:
0.753913186469598763502963347.
Python code:
import math
def dxdt(t, x):
return (3*(x**2)*math.cos(5*t))
# Finds value of x for a given t using step size h
# and initial value x0 at t0.
def rungeKutta(t0, x0, t, h):
# Count number of iterations using step size or
# step height h
n = (int)((t - t0)/h)
# Iterate for number of iterations
x = x0
for i in range(1, n + 1):
"Applx Runge Kutta Formulas to find nett value of x"
k1 = h * dxdt(t0, x)
k2 = h * dxdt(t0 + 0.5 * h, x + 0.5 * k1)
k3 = h * dxdt(t0 + 0.5 * h, x + 0.5 * k2)
k4 = h * dxdt(t0 + h, x + k3)
# Update nett value of x
x = x + (1.0 / 6.0)*(k1 + 2 * k2 + 2 * k3 + k4)
# Update nett value of t
t0 = t0 + h
return x
# Driver method
t0 = 0.0
x = 1.0
t = 2.0
a = [0.1, 0.05 , 0.025 , 0.0125 , 0.00625 , 0.003125 , 0.0015625]
i = 1
for i in range(len(a)):
print("The value of x at with step-size %.7f is: %.27f"%(a[i], rungeKutta(t0, x, t, a[i])))
print("Error at t=2 is: ",0.753913186469598763502963347-rungeKutta(t0, x, 2, 0.0015625))
The value of x for given step-sizes and the error at t = 2 is given in the program output below:
(Feel free to ask if you have any doubts and give an upvote if you got it. Thanks)