How Random is randint()?
Well, I had my doubts about randint() so I decided to test it out. I whipped up a little code in order to do so.
from random import randint
from console import clear
zero = one = two = three = 0
ergo = 0
clean = 0
while ergo < 1000000:
#Randomly choses 0,1,2,or3
spin = randint(0,3)
#Keeps track of how often a given number comes up
if spin == 0:
zero += 1
elif spin ==1:
one += 1
elif spin == 2:
two += 1
elif spin == 3:
three += 1
ergo += 1
#This prints what number ergo is at, in thousands
if clean == 1000:
clean = 0
#Converts the tallies into percentages and then prints the results
rolls = [zero, one, two, three]
names = ["zero","one","two","three"]
for x in rolls:
spam = (x/1000000.0)*100
y += 1
To explain what this program does, it randomly choses one of four numbers (zero, one, two, or three). It then keeps a tally of which number it choses. It proceeds to do this a total of one million times!
After the computation is complete, it turns the tallies into percentages and prints the results. Because there are four numbers, each number should appear 25% of the time. Here is the results from my most recent running:
As you can see, each number appears (almost) 25% of the time. I'd say that randint() works pretty well.
Just a word to the wise, the program takes some time to run. Somewhere between five and ten minutes.
Yeah I have done a similar program to this in the past. Actually that slight variance in your program is only due to the fact you didn't test enough population. It should eventually converge on 25% of the time.
Randint is very solid :)
That may be due to the fact the decimals are so small that the program rounds up. I plan on trying one billion (just for fun), but I need to make sure the iPad doesn't die on me XD
Either way, randint() is reliable (to say the least).
To speed up the loop considerably, remove print and clear from the program. Printing a lot of times has the side effect of causing tremendous lag. I noticed this when debugging my games.
On my PC, I am able to get it to perform the 1 million loops in only 5 seconds. So I amped it up to 10 million..
Time took: 50.25
As expected, 10 times longer. Sooo I can safely amp it up to 100 million and just wait 10 minutes:
Time took: 528.875
It doesn't get much closer than that! I wouldn't suggest trying 1 billion since (on my computer) it would take 5000+ seconds.
If you want to see how long a loop runs, you can do something like this:
from time import time
start = time()
#insert program or loop here
print time()-start #print current time (in seconds)
You can always reset the start timer.
83 and 1/3 hours.... That would be quite some time!
And thanks for the tip on clear and print. I have another program that does a loop a lot, but it does print a bit. I'll see what I can cut. I assume sounds slow it down a bit too.
And thanks for the additional research!
Randint() is very solid!