and here is the original code in Python: def euler (fcn, y0, t0,tend,dt): Yn = y
ID: 3109136 • Letter: A
Question
and here is the original code in Python:
def euler (fcn, y0, t0,tend,dt):
Yn = y0
tn = t0
ERRmax = 0
for n in range (0, MaxN+1):
Yn = Yn + dt*fcn(tn,Yn)
tn = tn + dt
yexact = exp(tn)
ERRn = abs(yexact - Yn)
ERRmax = max(ERRmax,ERRn)
print ('{:4.0f} {:12.6f} {:12.4f} {:18.15f} {:18.15f} {:18.15f} '.format(n, tn, Yn, yexact, ERRn, ERRmax))
Explanation / Answer
clc;
clear all;
f1=@(y1,y2,t) y2;
f2=@(y1,y2,t) y1;
n=input('n=')
h=1/n;
t=0:h:1;
y1(1)=1;
y2(1)=0;
for i=1:n
y1(i+1)=y1(i)+h*f1(y1(i),y2(i),t(i));
y2(i+1)=y2(i)+h*f2(y1(i),y2(i),t(i));
end
for i=1:n
y_exact(i)=cosh(t(i));
end
for i=1:n
y_error(i)=abs(y_exact(i)-y1(i));
end
max_error=0;
%for i=1:n
max_error=max(max_error,y_error);
%end
for i=1:n
fprintf('%f %f %f %f %f ',t(i),y1(i),y_exact(i),y_error(i),max_error(i))
end
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.