Solving a first order ODE with Euler backwards method

104 visualizaciones (últimos 30 días)
Ibrahim Ali
Ibrahim Ali el 1 de Oct. de 2021
Respondida: Alan Stevens el 2 de Oct. de 2021
I'm trying to solve the ODE below: F_ty = @(t,y) (2*t-4)*exp(-y); using Euler backwards method with the intial condition y(5) = 0. But I keep getting these two error messages, any help would greatly be appreciated, thanks in advance! The following two errors are:
Exiting fzero: aborting search for an interval containing a sign change
because NaN or Inf function value encountered during search.
(Function value at -799.643 is -Inf.)
Check function or try again with a different starting value.
Error using fzero (line 214)
Second argument must be finite.
Error in backwardeuler (line 22)
y(i+1) = fzero(@(Y) y(i) + dt*((2*t(i+1)-4)*exp(-Y)) - Y, y(i), options);
--------------------------------------------------------------------------------
% y_true = log(t^2 -4*t-4); Initial condition y(5) = 0;
% F_ty = @(t,y) (2*t-4)*exp(-y);
dt = 0.01;
t0 = 0;
tf = 3;
t = t0:dt:tf;
y(5) = 0;
% using the formula for backward euler: y(i+1) = y(i) + dt*f(y(i+1),t(i+1))
% we get
%y(i+1) = y(i) + dt*((2*t(i+1)-4)*exp(-y(i+1)));
% setting the LHS equal to zero so we can use fsolve:
% 0 = y(i) + dt*((2*t(i+1)-4)*exp(-y(i+1))) - y(i+1);
% We define y(i+1) = Y, so that
% 0 = y(i) + dt*((2*t(i+1)-4)*exp(-Y)) - Y;
options = optimset('TolX',1e-06);
for i = 1:length(t)-1
y(i+1) = fzero(@(Y) y(i) + dt*((2*t(i+1)-4)*exp(-Y)) - Y, y(i), options);
y_exact(i+1) = log((t(i+1))^2-4*t(i+1)-4);
end
Exiting fzero: aborting search for an interval containing a sign change because NaN or Inf function value encountered during search. (Function value at -799.643 is -Inf.) Check function or try again with a different starting value.
Error using fzero (line 214)
Second argument must be finite.
figure(1)
hold on
plot(t,y,'bo')
plot(t,y_exact,'r-')
xlabel('time')
ylabel('y(t)')
title('Backward Euler method vs exact solution')
legend('Backward Euler', 'Exact')

Respuesta aceptada

Alan Stevens
Alan Stevens el 2 de Oct. de 2021
Your y_true is only valid for t>= 5 (smaller values give imaginary results for y). So, try going from 5 to 8:
% y_true = log(t^2 -4*t-4); Initial condition y(5) = 0;
% F_ty = @(t,y) (2*t-4)*exp(-y);
dt = 0.01;
t0 = 5;
tf = 8;
t = t0:dt:tf;
y(5) = 0;
for i = 1:length(t)-1
y(i+1) = fzero(@(Y) y(i) + dt*((2*t(i+1)-4)*exp(-Y)) - Y, y(i));
y_exact(i+1) = log((t(i+1))^2-4*t(i+1)-4);
end
figure(1)
hold on
plot(t,y,'bo')
plot(t,y_exact,'r-')
xlabel('time')
ylabel('y(t)')
title('Backward Euler method vs exact solution')
legend('Backward Euler', 'Exact')

Más respuestas (0)

Categorías

Más información sobre Ordinary Differential Equations en Help Center y File Exchange.

Etiquetas

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by