


Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!



Math 151B Homework #2 – due Friday 1/23, in class
Consider the following initial value problem
y′^ = t−^2 (sin 2t − 2 ty), 1 ≤ t ≤ 10 , y(1) = 2
which has exact solution y(t) = (2t^2 )−^1 (4 + cos 2 − cos 2t).
a. Use Euler’s method with h = 0.25 to approximate the solution. Answer: Use the code from assignment 1, but with the function file function f = f(t,y) f = (sin(2t)-2t*y)/(t^2); endfunction
b. Use the fourth order Runge-Kutta method with h = 0.25 to approximate the solution. Answer: Create a file rk4.m containing function [t,w] = rk4(fname,a,b,alpha,N) f = str2func(fname); h = (b-a)/N; t(1) = a; w(1) = alpha; for i=1:N k1 = hf(t(i),w(i)); k2 = hf(t(i)+h/2,w(i)+k1/2); k3 = hf(t(i)+h/2,w(i)+k2/2); k4 = hf(t(i)+h,w(i)+k3); w(i+1) = w(i) + (k1+2k2+2k3+k4)/6; t(i+1) = t(i) + h; endfor endfunction This will output two arrays contianing ti and wi.
c. Plot these results, along with the exact solution. Answer: We plot them with the script hold on; clearplot; gnuplot_set key right;
t = 1:0.25:10; y = (4+cos(2)-cos(2t))./(2t.^2);
plot(t,y,";Exact;-o1");
[t,w] = euler("f",1,10,2,36); plot(t,w,";Euler;-+2");
[t,w] = rk4("f",1,10,2,36); semilogy(t,w,";RK4;-*3");
print -dpsc2 rk4.ps hold off; and get
1
10
1 2 3 4 5 6 7 8 9 10
Exact Euler RK
which shows RK4 to be much better than Euler.
Write a variable step size method, using Euler’s method and modified Euler’s method. Using a tolerance of 10−^2 , hmax = 1.0 and hmin = 0.1, approximate the solution to problem 1, and compare graphically.
Do the same with hmax = 2.0 and hmin = 0.5. This will use fewer points than Euler’s method. How does it compare in accuracy?
% warn if qmin is not small enough if qold <= qmin printf("Warning: hmin not small enough.\n"); endif
endwhile endfunction
which gives us
1
10
1 2 3 4 5 6 7 8 9 10
Exact Euler RKF12 tol=0. RKF12 tol=0.
The numbers for hmin are not small enough for this tolerance. If we play around with the numbers, we see that we can get very good accuracy, but at a cost of more function evaluations. However, we can still beat Euler’s method with fewer points.