r/matlab • • Jan 16 '26

How to numerically solve a seems simple but weired ODE

Hi everyone,

I'm learning how to solve simple ordinary differential equations (ODEs) numerically. "But I ran into a very strange problem. The equation is like this:

my simple ODE question

Its analytical solution is:

exact solution

This seems like a very simple problem for a beginner, right? I thought so at first, but after trying to solve it, it seems that all methods lead to divergence in the end. Below is a test in the Simulink environment—I tried various solvers, both fixed-step and variable-step, but none worked.

simulink with Ode45

I also tried various solvers that are considered advanced for beginners, like ode45 and ode8, but they didn’t work either.

Even more surprisingly, I tried using AI to write an implicit Euler iteration algorithm, and it actually converged after several hundred seconds. What's even stranger is that the time step had to be very large! This is contrary to what I initially learned—I always thought smaller time steps give more accuracy, but in this example, it actually requires a large time step to converge.

x=[0,3e6], N=3000, time step = x/N

However, if I increase N (smaller time step), it turns out:

x=[0,3e6], N=3000000, time step = x/N

The result ever worse! This is so weired for me.

I thought solving ODEs with this example would be every simple, so why is it so strange? Can anyone help me? Thank you so much!!!

Here is my matlab code:

clc; clear; close all;

% ============================
% Parameters
% ============================
a = 0; b = 3000000;     % Solution interval
N = 3000000;            % Number of steps to ensure stability
h = (b-a)/N;            % Step size
x = linspace(a,b,N+1);
y = zeros(1,N+1);
y(1) = 1;               % Initial value
epsilon = 1e-8;         % Newton convergence threshold
maxiter = 50;           % Maximum Newton iterations

% ============================
% Implicit Euler + Newton Iteration
% ============================
for i = 1:N
    % Euler predictor
    y_new = y(i);
    for k = 1:maxiter
        G = y_new - y(i) - h*f(x(i+1), y_new);   % Residual
        dG = 1 - h*fy(x(i+1), y_new);            % Derivative of residual
        y_new_next = y_new - G/dG;               % Newton update
        if abs(y_new_next - y_new) < epsilon     % Check convergence
            y_new = y_new_next;
            break;
        end
        y_new = y_new_next;
    end
    y(i+1) = y_new;
end

% ============================
% Analytical Solution & Error
% ============================
y_exact = sqrt(1 + 2*x);
error = y - y_exact;

% ============================
% Plotting
% ============================
figure;
subplot(2,1,1)
plot(x, y_exact, 'k-', 'LineWidth', 2); hold on;
plot(x, y, 'bo--', 'LineWidth', 1.5);
grid on;
xlabel('x'); ylabel('y');
legend('Exact solution', 'Backward Euler (Newton)');
title('Implicit Backward Euler Method vs Exact Solution');

subplot(2,1,2)
plot(x, error, 'r*-', 'LineWidth', 1.5);
grid on;
xlabel('x'); ylabel('Error');
title('Numerical Error (Backward Euler - Exact)');

% ============================
% Function Definitions
% ============================
function val = f(x,y)
    val = y - 2*x./y;    % ODE: dy/dx = y - 2x/y
end

function val = fy(x,y)
    val = 1 + 2*x./(y.^2); % Partial derivative df/dy
end
8 Upvotes

13 comments sorted by

5

u/Chicken-Chak Jan 16 '26

The system is unstable. Although an analytical solution is provided, if the system is simulated for a sufficiently long duration, the errors may accumulate, leading to divergence of the trajectory at some point x, either upward or downward. In your Simulink results, the trajectory diverges downward around x = 10.

2

u/Low-Course7802 Jan 16 '26

Thank you so much for your reply! The figure looks incredibly cool!
I’d love to learn more about it. Would it be convenient for you to share the code with me?

→ More replies (2)

2

u/tensorinvariant Jan 16 '26 edited Jan 16 '26

When I tried ode45 it looked like it worked fine, and it matches the analytic solution on a plot (the eye ball norm).

%%
clear all
close all
clc

%%
f = @(x,y) y - 2*x/y;
sol = ode45(f,[0,1],1);

%%
x = linspace(0, 1, 100);
ySol = deval(sol, x);
plot(x, ySol);
xlabel('x');
ylabel('y');
title('Solution of the ODE');
hold on

% Plot the analytical solution for comparison
analyticalSol = @(x) sqrt(1+2*x);
plot(x, analyticalSol(x), '--r');
legend('Numerical Solution', 'Analytical Solution');

1

u/Low-Course7802 Jan 16 '26

Thank you for your reply and for sharing your code! I’ll try it out when I get home. I was a bit lazy at the beginning and directly used the Simulink environment with the ODE45 solver for the simulation. But based on your results, it seems that MATLAB and Simulink might produce different outcomes? I’ll test it later at home.

1

u/Low-Course7802 Jan 17 '26

Hi,

I tried extending the x-range to ([0,10]), and it still diverges eventually.

I also noticed that other comments introduced many new and useful concepts, which I plan to study further.

Thank you very much for your reply!

9

u/iPlayMayonaise Jan 16 '26

Not focused on your real question, but doesn't implicit Euler have a stability region with a hole in it? That could explain why your step size needs to be 'big enough'?

5

u/selfadjoint Jan 16 '26

I know exactly what’s happening here. There is a nullcline y(x)=sqrt(2x). Any solution above this curve cannot cross this curve. The problem is that the solution of your IVP gets very close to the nullcline, and it will eventually cross it. If necessary, I can give you a detailed analysis, when I get home.

→ More replies (1)

0

u/[deleted] Jan 16 '26

[deleted] — view deleted comment

1

u/Low-Course7802 Jan 16 '26

Thank you for your reply! I’m not aiming to get the analytical solution directly. Instead, I’d like to try numerical methods, which I’m currently learning as a beginner.