and differentiating to obtain
y'= -y/t + 2 sqrt(y/t)cos(t)
We wrote the program rk4.c to approximate y(3) from the initial y(1)=sin2(1) using the RK4 method.
Output from the program for the RK4 method was
y(3)= 6.638285563573941e-03 Y3= 6.638285558272329e-03 E= 5.301611580299515e-12
To compare RK4 with Euler's explicit method we changed the main loop to read as
for(int i=0;i<n;i++){ double t=t0+i*h; y+=h*f(t,y); }Output from the modified program using Euler's method was
y(3)= 6.524827660108781e-03 Y3= 6.638285558272329e-03 E= -1.134578981635487e-04While RK4 is more complex and takes 4 function evaluations per times step the error is much smaller than Euler's method. A fair comparision, in terms of the number of function evaluations of f, could be made by allowing Euler's method to take 4 times as many steps. In this case Euler's method produces
y(3)= 6.609982887022521e-03 Y3= 6.638285558272329e-03 E= -2.830267124980836e-05which is still much less accurate than the RK4 method. It is possible to make a more advanced analysis of the error in the RK4 method by making a log-log plot of how E depends on n.