Skip to content

Instantly share code, notes, and snippets.

@phydev
Created May 23, 2021 14:52
Show Gist options
  • Save phydev/8e4646a4cd231fcafbcaecb15b0a6a37 to your computer and use it in GitHub Desktop.
Save phydev/8e4646a4cd231fcafbcaecb15b0a6a37 to your computer and use it in GitHub Desktop.
Simple Lotka-Volterra implementation
import numpy as np
import matplotlib.pyplot as plt
def xdot(x, y, alpha, beta, gamma, delta):
"""
this function represents the rate of change of the prey population
"""
return alpha * x - beta * x * y
def ydot(x, y, alpha, beta, gamma, delta):
"""
this function represents the rate of change of the predator population
"""
return delta * x * y - gamma * y
T = 1000 # number of iterations
x = np.zeros(T) # allocating memory to save the system history
y = np.zeros(T)
x[0] = 10. # prey initial population
y[0] = 10. # predator initial population
dt = 0.01
# defining the parameters
params = {'alpha': 0.5,
'beta': 0.5,
'delta': 0.5,
'gamma': 0.5}
# time integration loop
for t in range(0,T-1):
x[t+1] = x[t] + dt * xdot(x[t], y[t], **params)
y[t+1] = y[t] + dt * ydot(x[t], y[t], **params)
# output and plots
plt.plot(x, label='Presa', color='black', ls=':')
plt.plot(y, label='Predador', color='blue', ls='--')
plt.legend()
plt.xlabel('Time (a.u)')
plt.ylabel('Population')
#plt.savefig('result_lotka-volterra.png', dpi=300) # uncomment for saving to a png file
plt.show()
plt.plot(x, y)
plt.xlabel('presa')
plt.ylabel('predador')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment