필터 지우기
필터 지우기

Euler's Method

조회 수: 11 (최근 30일)
John
John 2011년 3월 27일
댓글: Hiba Ahmed 2017년 12월 8일
Using the Euler method solve the following differential equation. At x = 0, y = 5.
y' + x/y = 0
Calculate the Numerical solution using step sizes of .5; .1; and .01
From my text book I have coded Euler's method
function [t,y] = eulode(dydt, tspan, y0, h)
%eulode: Euler ODE solver
% [t,y] = eulode(dydt, tspan, y0, h, p1, p2,...)
% ` uses EULER'S method to INTEGRATE an ODE
% (uses the slope at the beginning of the stepsize to graph the
% function.)
%Input:
% dydt = name of hte M-file that evaluates the ODE
% tspan = [ti,tf] where ti and tf = initial and final values of
% independent variables
% y0 = initial value of dependent variable
% h = step size
% p1,p2 = additional parameter used by dydt
%Output:
% t = vector of independent variable
% y = vector of solution for dependent variable
if nargin<4, error('at least 4 input arguments required'), end
ti = tspan(1); tf = tspan(2);
if ~ (tf>ti), error('upper limit must be greater than lower limit'), end
t = (ti:h:tf)';
n = length(t);
%if necessary, add an additional value of t
%so that range goes from t=ti to tf
if t(n)<tf
t(n+1) = tf;
n = n+1;
t(n)=tf;
end
y = y0*ones(n,1); %preallocate y to improve efficiency
for i = 1:n-1 %implement Euler's Method
y(i+1) = y(i) + dydt(t(i),y(i))*(t(i+1)-t(i));
end
plot(t,y)
I have made another m-file to run Eulode, what I am confused with is where do I input my different step sizes and where do I input x=0 and y=5. However since the analytical solution yields:
simplify(dsolve('Dy=-x/y','y(0)=5','x'))
ans =
(-x^2+25)^(1/2)
and when x=0 the value is 5 so I have coded my Euler's Method like the following and the final values are close to 5 so I think it is correct can someone just verify.
dydx=@(x,y) -(x/y);
[x1,y1]=eulode(dydx, [0 1],5,.5);
[x2,y2]=eulode(dydx,[0 1],5,.1);
[x3,y3]=eulode(dydx,[0 1],5,.01);
disp([x1,y1])
disp([x2,y2])
disp([x3,y3])
  댓글 수: 1
Hiba Ahmed
Hiba Ahmed 2017년 12월 8일
what about if you have a system of 2 differential equations?

댓글을 달려면 로그인하십시오.

답변 (1개)

Walter Roberson
Walter Roberson 2011년 3월 27일
Yup, you have provided the values in the correct positions according to the documentation for eulode.
  댓글 수: 2
John
John 2011년 3월 27일
I think it is correct too, but should the eulode not become more accurate with a smaller step size? (with this configuration .01 has a larger error than .1 and .5)
Matt Tearle
Matt Tearle 2011년 3월 28일
How are you determining the error? If you're using the calculation you used here http://www.mathworks.com/matlabcentral/answers/4165-plotting-error then that's an incorrect calculation. So your use of the code here is fine, and Euler's method is indeed more accurate with a smaller stepsize.

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Programming에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by