Math 4330 Sec. 1, Matlab Assignment # 4 , April 26, 2006 Name. 1 Numerical
Solution of ODEs Using Matlab. 1.1 Euler's Method. Euler's one step method is ...
Math 4330 Sec. 1, Matlab Assignment # 4 , April 26, 2006 Name
1
Numerical Solution of ODEs Using Matlab
1.1
Euler’s Method
Euler’s one step method is undoubtedly the simplest method for approximating the solution to an ordinary differential equation. It goes something like this: Given a first order initial value problem x0 = f (t, x), t ∈ (a, b)
(1)
x(a) = xa
(2)
we observe that defining tj = a + hj, for j = 0, 1, 2, · · · , N where h = (b − a)/N we have x(tj+1 ) − x(tj ) ≈ f (tj , x(tj )). h Therefore we can write x(tj+1 ) ≈ x(tj ) + h f (tj , x(tj )). With this we can define an iterative scheme for computing approximations xj for x(tj ) using the iterative scheme xj+1 = xj + f (tj , xj ), j = 0, 2, · · · , (N − 1). As an example let us consider the IVP x0 (t) = −tx(t), x(0) = 1 on 0 < t < 5. The exact solution is given by 2
x (t) = e−1/2 t . We build the m-file eul1d.m and save it to disk (use cd T:\ to change to the T drive) % Euler’s method 1 clear all defn=inline(’-t*x’,’t’,’x’); a=0; b=5; N=100; xa=1; h=(b-a)/N; t=a+h*(0:N); LT=length(t); x(1)=xa; for j=2:LT x(j)=x(j-1)+h*defn(t(j-1),x(j-1)); end xact_sol=exp(-t.^2/2); plot(t,x,’b’,t,xact_sol,’r--’,’LineWidth’,2) Execute the file in the Workspace by typing the first name of the file without the .m extension. We plot the result of executing this Matlab code, on 0 ≤ t ≤ 5 with initial condition x(0) = 1, in the following figure. 1
1
0.8
0.6
0.4
0.2
0 0
1
2
3
4
5
Exact Solution dotted Line This method can also be applied to higher dimensional problems as demonstrated in the following example. Consider the second order initial value problem x00 = f (t, x, x0 ), t ∈ [a, b] x(a) = xa x0 (a) = xpa If we set y = x0 , then the sxstem can be written as d x y = f (t, x, y) dt y x(a) = xa y(a) = xpa The numerical approximation can now be carrried out just as above. As we have already mentioned it is very difficult to find exact solutions to most interesting problems. The next example is a second order initial value problem. Consider x00 (t) =
−tx(t) , + 1)
(x0 (t)2
x(0) = 1, x0 (0) = 1,
Now we build an m-file eul2d.m to solve the problem. clear % Euler’s method 2d clear defn=inline(’[y;-t*x/(y^2+1)]’,’t’,’x’,’y’); a=0; b=5; N=200; h=(b-a)/N; t=a+h*(0:N); LT=length(t); xa=1; xpa=1; w(:,1)=[xa;xpa]; for j=2:LT w(:,j)=w(:,j-1)+h*defn(t(j-1),w(1,j-1),w(2,j-1)); end x=w(1,:); plot(t,x,’LineWidth’,2) grid on 2
on 0 < t < 5.
We plot the result of executing this Matlab code in the following figure. 2 1.5 1 0.5 0 −0.5 −1 −1.5 −2 0
1
2
3
4
5
For any numerical method the Final Global Error (FGE) is defined as E(x(b), h) = |x(b) − xN |. It can be shown that Euler’s method is order one in h, i.e., E(x(b), h) = Ch where C is a constant that depends on f (t, x). There are many variations on the Euler method. Some of them are given in the first exercise in the next section. They are all of higher order than Euler’s method.
1.2
Modified Euler’s Methods
Once again we consider (1) and apply the fundamental theorem of calculus to get Z t2 Z t2 f (t, x(t)) dt = x0 (t) dt = x(t2 ) − x(t1 ). t1
t1
This implies that Z
t2
x(t2 ) = x(t1 ) +
f (t, x(t)) dt. t1
Now we consider two possible ways to approximate the integral on the right above. The Midpoint Rule: The midpoint method uses Euler to step halfway across the interval, evaluates the function at this intermediate point, then uses that slope to take the actual step.
s1 = f (tk , xk ) h h s2 = f tk + , xk + s1 2 2 xk+1 = xk + hs2 tk+1 = tk + h This formula is obtained as follows: First we replace the approximation x0 (t) =
x(t + h) − x(t) h 3
by the more accurate approximation (see the figure) h x(t + h) − x(t) 0 x t+ = 2 h
Then we apply Taylor’s formula of order one g(ξ) = g(a) + g 0 (a)(ξ − a) + O(((ξ − a)2 ), to the left hand side with ξ = t + h/2, a = h/2 and g = x, to obtain h h h h 0 h ≈ x(t) + x (t) = x(t) + f t + , y t + . x t+ 2 2 2 2 2
h x t+ 2
h h ≈ x(t) + x0 (t) = x(t) + f (t, x(t)). 2 2
So we finally arrive at h x(t + h) ≈ x(t) + f 2
h h t + , x(t) + f (t, x(t)) . 2 2
The Trapezoid Rule: For the trapezoid rule we approximate the integral with step size h = t2 − t1 using h x(t2 ) ≈ x(t1 ) + [f (t1 , x(t1 )) + f (t2 , x(t2 ))]. 2 Unfortunately, we do not know x(t2 ) on the right side, so we use, for example, Euler’s method to approximate it: x(t2 ) ≈ x(t1 ) + hf (t1 , x(t1 )). We thus obtain a numerical procedure by denoting x(tk ) by yk for each k and setting pk = xk + hf (tk , xk ), tk+1 = tk + h, h xk+1 = xk + [f (tk , xk ) + f (tk+1 , pk )] . 2
4
1.3
Matlab Builtin ODE Solvers
In addition there are many other methods for approximating solutions to ordinary differential equations, but due to a lack of time left in the semester I will just introduce you to Matlabs built-in Runge-Kutta solver ode45 and show you how it works. The basic syntax for using ode45 is the following [t,x] = ode45(’xdot’,tspan,x0) where xdot.m is a function file containing the the right hand side of the differential equation, tspan is a vector of time values at which you want to obtain the solution and x0 is the initial condition. Lets consider the first example considered above x0 (t) = −tx(t),
x(0) = 1 on 0 < t < 2.
We build the function file xdot.m given by function dx=xdot(t,x) dx = -t*x; Next we build a matlab script, call it say run_xdot.m, that we use to run ode45, plot the results, etc.
clear all a=0; b=2; tspan=linspace(a,b,20*fix(b-a)); x0=1; [t,x]=ode45(’xdot’,tspan,x0); xact_sol=exp(-t.^2/2); plot(t,x,’b’,t,xact_sol,’r--’,’LineWidth’,2) Let us compare the Euler and ode45 methods results. A detailed theoretical development shows that the Euler method is an order one method. which means that for a given problem there is a constant C so that the error between the exact solution and the numerical solution behaves like Ch where you recall that h = (b − a)/N . So if we cut h in half we expect to see the error cut in half. To show that this is what happens for Euler’s method we combine our earlier Euler code with the above ode45 code and take a sequence of values for N given by N = 20(2k ) for k = 1, 2, 3, 4. Thus we start with N = 40, then 80, etc. For the ode45 code we do set a value of h since it used an adaptive method to maintain a given error. The default is about 10−4 but you can set it to any value. The results in the following table clearly show the described behavior. N
h
Euler
ode45
40
0.12500
0.031
0.000120
80
0.06250
0.015
0.000061
160 0.03125
0.007
0.000134
320 0.01562
0.004
0.000087
5
% Compare Euler and ode45 clear all defn=inline(’-t*x’,’t’,’x’); a=0; b=5; xa=1; %%%%%%%%%%%%%%%%% disp(’ ’) disp(’ N h Euler ode45’) disp(’---------------------------------’) for k=1:4 N=20*2^k; h=(b-a)/N; tspan=a+h*(0:N); %%%%%%%%% Euler solve x_euler(1)=xa; for j=1:N x_euler(j+1)=x_euler(j)+h*defn(tspan(j),x_euler(j)); end %%%%%%%% ode45 solve [T,x]=ode45(’xdot’,tspan,xa); %%%%%%% exact solution xact_sol=exp(-T.^2/2); %%%%%%% errors err=max(abs(x-xact_sol)); err_euler=max(abs(x_euler-xact_sol’)); %%%%%%% display results disp(sprintf(’%3.0f %5.5f %0.3f %0.6f ’, N,h,err_euler,err)) end Now lets look at a much more interesting example. The next example is version of the van der Pohl oscillator given by the following second order initial value problem on an interval (0, T ), for T > 0. d2 z dz + µ(z 2 − 1) + z = 0 2 dt dt dz z(0) = z0 , (0) = z1 dt We transform this problem to a first order system by introducing " # y1 dz y1 = z and y2 = and defining y = . dt y2 With this we can write " # " # y2 d y1 = dt y2 µ(1 − y12 )y2 − y1 y(0) =
" # z0 z1 6
To solve this problem numerically we build a function file named vdpde.m function yp = vdpde(t,y) global MU yp(1)=y(2); yp(2)=MU*y(2).*(1-y(1).^2)-y(1); Now we build an m-file run_vdp.m to setup and run the problem. We start with MU=1 but as you change this value, you will notice that the “limit cycle” can change considerably. Run the problem for several different initial conditions for the same MU and you will see why we speak of a limit cycle. clear clear global global MU t0=0; T=100; MU=1; v= [1;2]; tvec=t0:.025:T; [t,y]=ode45(’vdpde’,tvec,v); plot(y(:,1),y(:,2)) % plot of phase portrait In the following figure we have plotted the numerical solution with two initial conditions v= [0;.1] and v=[2;-1] and we have included a plot of the direction field. We have plotted the phase portrait which means we have plotted y1 versus y2 . What we see is that for any initial conditions the trajectories approach a so-called limit cycle (a closed curve in the plane). Initial conditions inside the curve give trajectories that spiral outward to the curve and initial conditions outside the curve give trajectories that spiral inward to the curve. The shape of the curve depends on µ. 4 3 2 1 0 −1 −2 −3 −4 −4
−2
0
2
4
van der Pohl oscillator with µ = 1 As another example consider the famous Lorenz equations whose solution exhibits the so-called lorenz attractor. dx1 = σ(x2 − x1 ); dt dx2 = ((1 + r) − x3 )x1 − x2 ; dt dx3 = x1 x2 − bx3 ; dt Build a function file lorenzde.m 7
function dxdt=lorenzde(t,x); % The RHS of the Lorenz attractor sigma = 10; r = 28; b = 8/3; dxdt=[ sigma*(x(2)-x(1)); (1+r)*x(1)-x(2)-x(1)*x(3); x(1)*x(2)-b*x(3)]; Now build a file lorenz_run.m to run the problem clear all % a clear start t=[0 50]; % time window y0=[-10;10;25] % initial conditions [t,Y] = ode45(’lorenz’,t,y0); figure plot3(Y(:,1),Y(:,2),Y(:,3)) view([3,16]) grid on figure comet3(Y(:,1),Y(:,2),Y(:,3))
50 40 30 20 50
10 0 0 −20
−10
0
10
The Lorenz Attractor
8
20
−50
ASSIGNMENT 6 – Math 4330 and 5344 1. This problem is concerned with comparing the accuracy of the two variations on the Euler’s method discussed in the text. (a) Euler x1 = xa , xj+1 = xj + hf (tj , xj ) h h (b) Midpoint x1 = xa , xj+1 = xj + hf tj + , xj + f (tj , xj ) 2 2 h (c) Modified Euler x1 = xa , xj+1 = xj + f (tj , xj ) + f (tj+1 , xj + hf (tj , xj )) 2 For this comparison use the follwing differential equation: x0 = x − tx3 e−2t , 0 ≤ t ≤ 1, x(0) = 1, exact solution: x = (t2 + 1)−1/2 et Write a Matlab script file that will: i) Close all existing figure windows by placing the command close all on the first line of your script and clear all to clear all variables. ii) Use initial conditions x(0) = 1. iii) Solve on the t interval [0, 1] using Euler (x_e), Midpoint (x_m) and Modified Euler (x_t) methods using N = 20(2k ) for k = 1, 2, 3, 4. To do this just modify the basic Euler program to include the midpoint and modified methods. iv) Make a table to compare the resulting accuracy by finding the maximum of the absolute value of the difference of the numerical solution for each method and the exact solution (as in the program in the text). v) Arrange your work in the following order. * A printout of your script file. * The printout of the table. 2. This problem is concerned with using ode45 to solve the harmonic oscillator problem y 00 + 4y = 0,
y(0) = 1,
y 0 (0) = 0.
The first step is to write the problem as a first order system with x1 = y and x2 = y 0 : dx1 dx2 = x2 , = −4x1 dt dt x1 (0) = 1, x2 (0) = 0 The exact solution to this problem is y(t) = cos(2t). A. Write a function file named harm_de.m defining the first order system of equations. B. Write a script to use a starting time t0 = 0 and a stopping time T = 4π with tspan = linspace(t0 , T, 300) and solve the problem using ode45. C. On separate figure windows plot (t, x1 ), (t, x2 ) and (x1 , x2 ). 9
3. This problem is concerned with the Duffing oscillator which is a two dimensional non-autonomous system that can exhibit chaotic dynamical behavior. “In 1918, Duffing introduced a nonlinear oscillator with a cubic stiffness term to describe the hardening spring effect observed in many mechanical systems.” (Guckenheimer and Holmes) dy d2 y + y 3 = γ cos(ωt). +δ 2 dt dt (a) Write the second order equation as a system of two first order equations. Use x1 = y and x2 = y 0 . (b) Write a function M-file for the system of equations in part (a). Use global variables for the parameters δ (use del), γ (use gam), and ω. (c) Write a Matlab script file that will: i) Close all existing figure windows by placing the command close all on the first line of your script and clear all to clear all variables. ii) Set the parameter values to δ = .15, γ = .3 and ω = 1. iii) Use initial conditions y(0) = −1 and y 0 (0) = 1. iv) Solve on the t interval [0, 100]. v) Plot the solution y(t) (i.e., x1 ). vi) Arrange your work in the following order. * A printout of your script file. * A printout of your function M-file for Duffings oscillator. * The printout of the solution.
References [1] The Matlab Primer, Kermit Sigmon [2] Introduction to scientific computing: a matrix vector approach using Matlab, Printice Hall, 1997, Charles Van Loan [3] Mastering Matlab, Printice Hall, 1996, Duane Hanselman and Bruce Littlefield [4] Advanced Mathematics and Mechanics Applications Using Matlab, CRC Press, 1994, Howard B. Wilson and Louis H. Turcotte [5] Engineering Problem Solving with Matlab, Printice Hall, 1993, D.M Etter [6] Solving Problems in Scientific Computing Using Maple and Matlab, Walter Gander and Jiri Hrebicek [7] Computer Exercises for Linear Algebra, Printice Hall, 1996, Steven Leon, Eugene Herman, Richard Faulkenberry. [8] Contemporary Linear Systems using Matlab, PWS Publishing Co., 1994, Robert D. Strum, Donald E. Kirk 10