In: Physics
Consider a simple electrical circuit where you charge a capacitor through a resistor by connecting a battery (closing the switch) at time t=0.
The charge Q on the capacitor is related to the current I by dQ/dt=I. Furthermore, by Kirchhoff’s law, V – RI – Vc =0, and the charge Q on the capacitor is Q=CVc, where C is the capacitance. That can be combined to give the differential equation
dQ/dt = V/R - Q/RC
The analytic solution is Q(t)=CV(1 – exp(-t/(RC)). Write a MATLAB code that solves the differentia equation with the Euler forward method, Predictor-Corrector method, and Runge Kutta 4th Order. Use values of 1F for the capacitor, 10 Ohm for the resistor, and 10 V for the battery. Run the code from 0 to 10 seconds. Use values for dt of 1.0, 0.1, and 0.01. For each of the runs calculate the percentage error at the end, and make a table of the errors. Discuss and submit the table and only the first plot for Euler/dt=1. Which dt and how many step do you need with each of the methods to achieve an accuracy of better than 0.01%?
dt=[1 .1 .01];
C=1;
R=10;
V=10;
ode=@(t,Q)(V/R-Q/(R*C));
exact=C*V*(1-exp(-10/(R*C)));
for j=1:3
h=dt(j);
t=0:h:10;
yHeun=zeros(size(t));
yHeun(1)=0;
yEul=yHeun;
for i=2:length(t)
w=yHeun(i-1)+h*ode(t(i-1),yHeun(i-1));
yHeun(i)=yHeun(i-1)+(h/2)*(ode(t(i-1),yHeun(i-1))+ode(t(i),w));
end
for i=2:length(t)
yEul(i)=yEul(i-1)+h*ode(t(i-1),yEul(i-1));
end
figure
plot(t,yEul)
title(['Euler method, dt = ',num2str(h)])
figure
plot(t,yHeun)
title(['Predictor Corrector method, dt = ',num2str(h)])
percEr_Eul=abs((yEul(end)-exact)/exact)*100;
percEr_Heun=abs((yHeun(end)-exact)/exact)*100;
fprintf('Euler Method, dt = %.2f,percentage error: %f\n',h,percEr_Eul)
fprintf('Predicter Corrector Method, dt = %.2f,percentage error: %f\n',h,percEr_Heun)
end
Command window