Motivation
Mathematical introductions to Euler method that we can find on the Internet require some insight to be transformed into working code. On the other hand, existing code samples are often convoluted and detached from the mathematical foundations of the method. My goal here is to present a really simple piece of code that solves a first order differential equation so that, without the use of any external libraries, anyone with basic understanding of Python and some interest in maths can understand the thing.Mathematical foundation
Please refer to https://en.wikipedia.org/wiki/Euler_method and its First-order example paragraph. The problem I personally see with this paragraph is the use of the expotential function as the illustration of the first-order equation. I think it will be much easier to understand if we use something easier, something that can be easily connected to a real world phenomenon.Population growth equation
A relatively easy equation is the one for population growth. Two terms that we need to define to reason about it are:- rate of natural increase - see https://en.wikipedia.org/wiki/Rate_of_natural_increase
- carrying capacity of the environment - see https://en.wikipedia.org/wiki/Carrying_capacity
Simply put, the rate of natural increase (r) tells us how fast the population is growing, based on births and deaths. The capacity (K) is the limitation of the environment to carry a population - a maximum number that still allows for the resources, such as food and water, to be available to the population. The equation we are going to solve is:
dy/dx = rN (1 - N/K)
where N is the population size. The solution to this equation will model the population growth over time.
The chart shows nicely how the population grows and when it reaches the environment limit and flattens out.
Code pointers
Full Python code is available at: https://github.com/pgorak/population-growth-euler- number of steps of the Euler method to execute
- step size (h)
- the first order function
- initial values of x and y
_makeSteps function actuall performs the steps in a loop and appends the results to the lists of X and Y coordinates.
dxdy function is our first order function - it is dependent on the x and y values calculated in the prior steps. Note: some first order functions may use just x or just y, some may use both. For example, our population growth function only uses y, while the polynomial function would use just x.
The dxdy function is turned into a callable using functools.partial so that it can be passed as an argument to makeSteps and called.
Try playing with different functions - a polynomial example is provided (commented out) in the code and you can also try out your own functions, also using sin, cos, etc. In some cases you will need to adjust the initial values of x and y.
