Skip to content

Instantly share code, notes, and snippets.

@libswan
Created May 11, 2013 13:12
Show Gist options
  • Save libswan/5559926 to your computer and use it in GitHub Desktop.
Save libswan/5559926 to your computer and use it in GitHub Desktop.
Correct code from kiwitrader
def rabbitGrowth():
"""
rabbitGrowth is called once at the beginning of each time step.
It makes use of the global variables: CURRENTRABBITPOP and MAXRABBITPOP.
The global variable CURRENTRABBITPOP is modified by this procedure.
For each rabbit, based on the probabilities in the problem set write-up,
a new rabbit may be born.
Nothing is returned.
"""
global MAXRABBITPOP
global CURRENTRABBITPOP
numRabbits = CURRENTRABBITPOP
# print 'initial', numRabbits
for r in range(CURRENTRABBITPOP):
pRabbitReproduction = 1 - (numRabbits / float(MAXRABBITPOP))
# if r < 10: print pRabbitReproduction,
if pRabbitReproduction <= 0 or numRabbits == MAXRABBITPOP:
CURRENTRABBITPOP = MAXRABBITPOP # they may require numRabbits
break
if random.random() <= pRabbitReproduction:
numRabbits += 1
CURRENTRABBITPOP = numRabbits
return
def foxGrowth():
"""
foxGrowth is called once at the end of each time step.
It makes use of the global variables: CURRENTFOXPOP and CURRENTRABBITPOP,
and both may be modified by this procedure.
Each fox, based on the probabilities in the problem statement, may eat
one rabbit (but only if there are more than 10 rabbits).
If it eats a rabbit, then with a 1/3 prob it gives birth to a new fox.
If it does not eat a rabbit, then with a 1/10 prob it dies.
Nothing is returned.
"""
global MAXRABBITPOP
global CURRENTRABBITPOP
global CURRENTFOXPOP
numRabbits = CURRENTRABBITPOP
numFoxes = CURRENTFOXPOP
pFoxReproduction = 1 / 3.0
pFoxDeath = 0.10
for r in range(CURRENTFOXPOP):
pFoxEats = numRabbits / float(MAXRABBITPOP)
if random.random() <= pFoxEats:
if numRabbits > 10:
numRabbits -= 1
if random.random() <= pFoxReproduction:
numFoxes += 1
else:
if random.random() <= pFoxDeath:
numFoxes -= 1
CURRENTRABBITPOP = numRabbits
CURRENTFOXPOP = numFoxes
return
def runSimulation(numSteps=200):
"""
Runs the simulation for `numSteps` time steps.
Returns a tuple of two lists: (rabbit_populations, fox_populations)
where rabbit_populations is a record of the rabbit population at the
END of each time step, and fox_populations is a record of the fox population
at the END of each time step.
Both lists should be `numSteps` items long.
"""
r = []
f = []
for n in range(numSteps):
# if (n)%5 == 0: print
rabbitGrowth()
# global CURRENTRABBITPOP
# CURRENTRABBITPOP = 1000
# print CURRENTRABBITPOP,
foxGrowth()
# print n, MAXRABBITPOP, CURRENTRABBITPOP, CURRENTFOXPOP, ' ',
# print; print
r.append(CURRENTRABBITPOP)
f.append(CURRENTFOXPOP)
return (r, f)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment