Simple Modified Euler Question

Hello,
I try to iterate a function using Modified Euler method. I want to update my deltaX in every step. If the result is bigger than my error, I want the new deltaX will be the half of the previous one. Therefore, number of iterations will be twice in each iteration. I cannot find where my mistake is. Here is my code. Thank you.
y(1)=1; %initial value
x(1)=0; % x start
xf=10; % x end
e=10^-6; %error
for h(i)=2^(-i); %step size
n=(xf-x(1))/h(i); %number of iterations
i=1:n
y(i+1)=y(i)+(h(i)/2)*(exp(-x(i))-y(i)+exp(-x(i+1))-y(i)+h(i)*...
(exp(-x(i))-y(i)));
x(i+1)=x(i)+h(i);
if abs(y((i+1)-y(i))/y(i))<=e
disp(y(10))
break;
end
continue
end
disp(y(10))

2 Kommentare

John D'Errico
John D'Errico am 18 Dez. 2016
Bearbeitet: John D'Errico am 18 Dez. 2016
How is this an error?
abs(y((i+1)-y(i))/y(i))
It is a relative difference from the previous time step.
In order for it to be an "error", you would need to know that the previous step was in fact, truth.
Anyway, I fail to see where you are trying to update the step size in any event.
What differential equation are you trying to solve? It is really bad programming practice to build that function directly into the Euler step itself.
I see one glaring error:
for h(i)=2^(-i);
You do not initialize i, so this is the imaginary number. The indexing makes no sense with an imaginary value as all indices must be real positive integers. Furthermore, it makes no sense to index your looping variable next to the for declaration.
Please see the documentation on for loops.

Melden Sie sich an, um zu kommentieren.

Antworten (0)

Gefragt:

am 18 Dez. 2016

Kommentiert:

am 19 Dez. 2016

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by