My Computer Science teacher gave us a task to calculate the average after one billion trials.
His exact assignment was this:
Consider generating a sequence of random numbers on the interval [0, 1) perhaps using Math.random() in a loop and adding them together. How many numbers would you expect to generate in such a sequence before the sum exceeds 1.0 ? (i.e. probability)
Write a program that simulates these trials a billion times and calculates the average length of the sequences. This is a neat exercise in nested loops.
Examples:
- 0.449 0.814
- length of sequence: 2
- 0.167 0.138 0.028 0.934
- length of sequence: 4
- 0.640 0.258 0.417
- length of sequence: 3
- 0.911 0.212
- length of sequence: 2
Average of the four lengths is 11/4 ≈ 2.75
What is the average of one billion random sequences?
My code was this:
import random
def genSequence():
storenums = 0
numTrials = 1000000000
for x in range(0,numTrials):
numberOfAttempts = 0
getToOne = 0
while (getToOne < 1): #keeps on generating random numbers and adding it to getToOne until it reaches 1 or is over 1
getToOne += random.random()
numberOfAttempts += 1
storenums = storenums + numberOfAttempts
#print (x)
#print(storenums)
calculateAverage(storenums,numTrials)
def calculateAverage(num,den):
average = num/den
print(average)
genSequence()
*Note: I am using repl.it to run my code so there is no main.
The problem with my code is that it can't reach 1 billion trials and stops working at around 227,035. I'm pretty sure this is a memory issue but I don't know how to fix this. What can I do so that it actually completes the billion trials and preferably not in an egregiously long amount of time.
EDIT: My teacher the result should be e, but that isn't the point as I just need to write the code. Getting e just means I did it right.