Rabbits and Foxes

mail@pastecode.io avatar
unknown
python
a month ago
2.3 kB
1
Indexable
Never
# Number of rabbits and foxes

r_initial = 500
f_initial = 1
alpha = 0.2
beta = 0.005
gamma = 0.001
delta = 0.2

r_t = r_initial
f_t = f_initial

for t in range(0, 15):
    print("At time t =", str(round(t)) + ",", "there are", round(r_t), "rabbits, and", round(f_t), "foxes")
    r_next = r_t + (alpha * r_t) - (beta * r_t * f_t)
    f_next = f_t + (gamma * f_t * r_t) - (delta * f_t)
    r_t = r_next
    f_t = f_next
    if r_t < 0:
        r_t = 0
    if f_t < 0:
        f_t = 0
        
        
# How long can 100 rabbits survive?

max_years = 0
max_f_initial = 0

for f_initial in range(1, 1001):
    r_initial = 100
    alpha = 0.2
    beta = 0.005
    gamma = 0.001
    delta = 0.2

    t = 0
    r_t = r_initial
    f_t = f_initial

    while r_t != 0:
        r_next = r_t + (alpha * r_t) - (beta * r_t * f_t)
        f_next = f_t + (gamma * f_t * r_t) - (delta * f_t)
        r_t = r_next
        f_t = f_next
        if r_t < 0:
            r_t = 0
        if f_t < 0:
            f_t = 0    
        t = t + 1

    years_survived = t - 1

    if years_survived > max_years:
        max_years = years_survived
        max_f_initial = f_initial
    
print("If there are", max_f_initial, "foxes at t = 0, the rabbit species will survive for", max_years, "years, which is the maximum possible number of years the rabbits can survive")



# Saving rabbits from extinction

r_initial = 1
found = False
r_equilibrium = 0
f_equilibrium = 0

while True:
    for f_initial in range(1, 201):
        alpha = 0.2
        beta = 0.005
        gamma = 0.001
        delta = 0.2

        r_t = r_initial
        f_t = f_initial

        while r_t != 0:
            r_next = r_t + (alpha * r_t) - (beta * r_t * f_t)
            f_next = f_t + (gamma * f_t * r_t) - (delta * f_t)

            # Break out of for loop since either rabbits or foxes went extinct
            if r_t <= 0 or f_t <= 0:
                break

            if r_t == r_next and f_t == f_next:
                found = True
                r_equilibrium = r_initial
                f_equilibrium = f_initial
                break

            r_t = r_next
            f_t = f_next
    
    if found:
        break

    r_initial = r_initial + 1

print("For", f_equilibrium, "foxes, and", r_equilibrium, "rabbits at t = 0, the fox and rabbit species will never be extinct.")
Leave a Comment