% Igor Yanovsky
% Teaching Assistant
% Math 151B
% 04/15/07
%
% Homework 2, Problem 3
%
%#####################################################################
%
% This program solves the ordinary differential equation
% 
%  dy/dt = 1+(t-y)^2,    2 <= t <= 3
%  y(2) = 1
% 
% using RUNGE-KUTTA MIDPOINT method. The function defining the ODE is
% defined in a separate Matlab function.
%
% This program also finds the error of the approximation by comparing the
% approximate solution and the exact solution  y(t) = t + (1/(1-t)).
% 
%#####################################################################

clear all

format long

% ODE Specification
%

t0 = 2.0;
tF = 3.0;
y0 = 1.0;

h =  0.5              % timestep
N = (tF-t0)/h         % number of timesteps

t = t0;
w(1) = y0;              % initial condition
yexact(1) = y0;
error(1) = 0;           % 


for(i=1:N)
    w(i+1) = w(i) + h*f( t + (h/2), w(i)+(h/2)*f(t,w(i))); % advances the ODE using MIDPOINT method
    t = t + h;
    yexact(i+1) = t + (1/(1-t));
    error(i+1) = abs(w(i+1) - yexact(i+1));
end

fprintf(1,'N = %3d',N);  fprintf(1,', h = %4.7e',h);  fprintf(1,', t = %4.2f',t);  fprintf(1,',\n');

'Runge-Kutta Midpoint solution w at successive steps'
w
'Exact solution y at successive steps'
yexact
fprintf(1,'error at last step = %5.10e', error );  fprintf(1, '\n');



   
clear all
