-1
def rabbit(t):

    num = r0*(e**(rb*t))+ fox(t-1)*0.3

    return num

def fox(t):

    num = f0*(e**(rf*t))+ rabbit(t-1)*0.15

    return num

So I am trying to graph the above 2 functions in matplotlib As you can see both functions are dependent on one another rabbit gets eaten by fox and if fox have more rabbit to eat it with grow faster

Problem is, this will throw a recursion depth error(clearly)

RecursionError: maximum recursion depth exceeded

However if I add basecase and recursive case

def rabbit(t):

    if(t>0):
        num = r0*(e**(rb*t))+ fox(t-1)*0.3
    else:
        num = r0
    return num

def fox(t):

    if(t>0):    
        num = f0*(e**(rf*t))+ rabbit(t-1)*0.15
    else:
        num = f0
    return num

to this I get this error

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • I think you're passing `t` as numpy array instead of int – Pablo C Jun 08 '23 at 12:48
  • 1
    How are you calling the functions? Currently, there is no error in the code presented. Consider a MRE. https://stackoverflow.com/help/minimal-reproducible-example – LudvigH Jun 08 '23 at 14:25

1 Answers1

0

Good day to you. The function you provided works as long as you define the variables and call it on a number. As an example this works just fine on my machine:

r0 = 1
rb = 1
f0 = 1
rf = 3
e = 2.818
def rabbit(t):
    if(t>0):
        num = r0*(e**(rb*t))+ fox(t-1)*0.3
    else:
        num = r0
    return num

def fox(t):
    if(t>0):    
        num = f0*(e**(rf*t))+ rabbit(t-1)*0.15
    else:
        num = f0
    return num
print(rabbit(30),fox(30))

The error message you get looks like a numpy error message and I think that you try to pass t as a numpy array. This is causing an issue because if(t>0) become ambiguous... t contains multiple elements ! If your intention is to plot rabbit and fox over an interval (let's say from -10 to 10) then you could do this instead using a list comprehension (you need to import matplotlib.pyplot as plt and numpy as np):

x = np.linspace(-10,10,1000)
rabbit_values = np.array([rabbit(t) for t in x])
fox_values = np.array([fox(t) for t in x])
plt.plot(x,fox_values, label='fox')
plt.plot(x,rabbit_values,label='rabbit')
plt.legend()
plt.show()

Does it help ?

LioWal
  • 56
  • 2