What's wrong with this Python program on Euler's forward algorithm?

In summary, the conversation discusses the implementation of Euler's forward algorithm for solving non-stiff ODEs. The function is called with various parameters and a graph is plotted using the values returned by the function. However, when compared to a similar function in MATLAB, the graph shows discrepancies that can be attributed to the numerical stability of the Euler's method. Further investigation reveals that increasing the number of steps can lead to a more accurate graph.
  • #1
Wrichik Basu
Science Advisor
Insights Author
Gold Member
2,119
2,692
Here is the function that I have written:
Python:
import numpy as np

def ode_euler_forward(odefun, y_initial, x_range, num_steps):
    """
    Solves a system of non-stiff ODEs using Euler's forward algorithm.

    Parameters
    ----------
    odefun : callable(x, y1, y2, ...)
        The function that represents the system of ODEs.
    y_initial : tuple
        The initial values of all the dependent variables in the form (y_1_initial, y_2_initial, ...)
        If there is only one variable, turn it into a tuple with a trailing comma: (y_initial,)
    x_range : tuple
        The start and the end values of the independent variable in the form (x_start, x_end)
    num_steps : int
        The number of steps to be used.

    Returns
    -------
    x, y : tuple
        The values of the independent variable, and corresponding values of each dependent variable in the form
        (np.ndarray, np.ndarray).
    """
    x_initial = x_range[0]
    x_end = x_range[1]

    h = (x_end - x_initial) / num_steps  # The size of each step

    y_initial = np.asarray(y_initial)[np.newaxis, :]

    # y = [[y_initial], [0, 0, ...], [0, 0, ...], ...]. Each row will hold the value from one iteration.
    y = np.vstack((y_initial, np.zeros((num_steps - 1, np.size(y_initial, 1)), dtype=float)))

    x = np.linspace(x_initial, x_end, num_steps)[np.newaxis, :].T

    for i in range(0, num_steps - 1):
        y[i + 1, :] = y[i, :] + h * odefun(x[i], y[i, :][np.newaxis, :])

    return x, y
and here is how I call the function:
Python:
import numpy as np
import matplotlib.pyplot as plt

m = 10
k = 15

def myODE(t, x): return np.array([x[0, 1], -k * x[0, 0] / m])[np.newaxis, :]

tSol, xSol_euler = ode_euler_forward(myODE, (0.0, 1.0), (0.0, 30.0), 501)

plt.plot(tSol, xSol_euler[:, 1], '-b', label=r'$x(t)$')
plt.plot(tSol, xSol_euler[:, 0], '-r', label=r'$v(t)$')
plt.legend(loc='best')
plt.grid(True, which='both')
plt.show()
Here is the graph that I get:

Figure_1.png

If I run the (almost) same program in MATLAB using ode45, here is the graph I get:

untitled.png

In Python, I have also written functions for RK2 midpoint, Heun's and Ralston's algorithms. If I solve the problem using the first one of those functions, I get the following graph:

Figure_2.png

This matches the plot from MATLAB, which means there is something wrong with the Euler's algorithm function that I have written. Can anyone please point out the error?
 
Last edited:
Technology news on Phys.org
  • #2
You may want to investigate the concept of numerical stability. The explicit Euler method is a very simple integrator to implement but unfortunately also one with the smallest region of stability.
 
  • Like
Likes Wrichik Basu
  • #3
Filip Larsen said:
You may want to investigate the concept of numerical stability. The explicit Euler method is a very simple integrator to implement but unfortunately also one with the smallest region of stability.
In the Wikipedia page for Euler's method, there is one small section on Numerical stability. The example written there shows that the algorithm becomes quite unstable for larger step sizes. I increased the number of steps to 50000, and I could reproduce the correct graph. Thanks a lot for the help!
 

Related to What's wrong with this Python program on Euler's forward algorithm?

1. What is Euler's forward algorithm and why is it important in Python programming?

Euler's forward algorithm is a numerical method used for solving differential equations. It is important in Python programming because it allows us to approximate the solution of a differential equation without having to solve it analytically, which can be computationally expensive.

2. What are the common errors encountered when implementing Euler's forward algorithm in Python?

Some common errors when implementing Euler's forward algorithm in Python include incorrect initialization of variables, using incorrect data types, and not accounting for division by zero errors.

3. How can I check if my Python program on Euler's forward algorithm is correct?

You can check your program by comparing the results to a known analytical solution or using a different numerical method to solve the same problem. Additionally, testing your program on different inputs and checking for consistency can also help identify any errors.

4. How can I improve the efficiency of my Python program on Euler's forward algorithm?

One way to improve efficiency is by optimizing the implementation of the algorithm, such as using built-in Python functions or data structures. Additionally, using a smaller time step or a more accurate numerical method can also improve the accuracy and efficiency of the program.

5. Are there any limitations to using Euler's forward algorithm in Python?

Yes, there are some limitations to using Euler's forward algorithm in Python. It can only approximate the solution of a differential equation, and it may not be accurate for all types of differential equations. Additionally, it may not work well for stiff equations, which require smaller time steps to accurately approximate the solution.

Similar threads

  • Programming and Computer Science
Replies
4
Views
4K
  • Programming and Computer Science
Replies
15
Views
1K
  • Programming and Computer Science
Replies
2
Views
1K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
1
Views
956
  • Programming and Computer Science
Replies
1
Views
2K
Replies
3
Views
3K
  • Programming and Computer Science
Replies
2
Views
2K
  • Programming and Computer Science
Replies
5
Views
2K
  • Programming and Computer Science
Replies
16
Views
2K
Back
Top