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 个评论
John D'Errico
2016-12-18
编辑:John D'Errico
2016-12-18
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.
Brendan Hamm
2016-12-19
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.
回答(0 个)
类别
在 帮助中心 和 File Exchange 中查找有关 Multirate Signal Processing 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!