Euler's Method Problem

조회 수: 3 (최근 30일)
Maxine Feride
Maxine Feride 2021년 4월 5일
답변: Walter Roberson 2021년 4월 5일
Hi guys. In the task, it is necessary to calculate by the Euler method with the initial condition y(x0)=y0 , [a;b] wiith epsilon 0.001.
I have a function, but it only works correctly if y^1
For example, when f=x^(-2)*y^3 will be an error function S = sym(x, n, a) and the program stops
euler('x^(-2)*y^3',[1 2],[1 4], 50, 0.001)
Maybe you can help me? What could be the problem?
function [] = euler( f,X0,AB,n0,eps )
% f - original function
% X0 - coordinates of the starting point from the segment from which to start splitting
% A - segment [a; b]
% n0 - the initial number of partitions of the segment
% e - accuracy
x0=X0(1);
y0=X0(2);
a=AB(1);
b=AB(2);
% X() - array of abscissa values dx=(b-a)/n0
% Y() - array of ordinate values dx=(b-a)/n0
dx=(b-a)/n0; % the length of the split segment
X(1)=x0;
Y(1)=y0;
for i=1:1:n0
syms x y
y0=y0+subs(subs(f,x,x0),y,y0)*dx;
x0=x0+dx;
X(i+1)=x0;
Y(i+1)=y0;
end
dx=dx/2; % reduce the length of the split segment by half
x0=X0(1);
y0=X0(2);
X1(1)=x0;
Y1(1)=y0;
% X1() - array of abscissa values dx=(b-a)/n0 * 0.5
% Y1() - array of ordinate values dx=(b-a)/n0 * 0.5
for i=1:1:2*n0
y0=y0+subs(subs(f,x,x0),y,y0)*dx;
x0=x0+dx;
X1(i+1)=x0;
Y1(i+1)=y0;
end
maax=max(abs(Y-Y1(1:2:end)));
Y1_=Y1;
x0=X0(1);
y0=X0(2);
figure(1)
hold on
grid on
plot(X,Y,'r'); % graph for the first case
plot(X1,Y1,'g'); % graph for the second case
m=0;
while (maax>eps)
m=m+1;
dx=dx/2;
X2(1)=x0;
Y2(1)=y0;
n=(b-a)/dx;
for i=1:1:n
y0=y0+subs(subs(f,x,x0),y,y0)*dx;
x0=x0+dx;
X2(i+1)=x0;
Y2(i+1)=y0;
end
maax=max(Y1_-Y2(1:2:end));
Y1_=Y2;
end
if m==0
fprintf('There is not enough accuracy for making 2 graphics\n');
else
plot(X2,Y2,'b');
end
for i=2:n+1
fprintf('x = %f\ty = %f\n',X2(i),Y2(i));
end
fprintf('It took %i pieces of fragmintation \n',n)
end

답변 (1개)

Walter Roberson
Walter Roberson 2021년 4월 5일
Since R2018b it has not been valid to use text symbolic expressions such as 'x^(-2)*y^3' for any operation except dsolve() [and that will be eliminated soon, if it has not been already.]
If you have text that represents a symbolic expression, you must not use str2sym() to convert it to symbolic expression.

카테고리

Help CenterFile Exchange에서 Symbolic Math Toolbox에 대해 자세히 알아보기

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by