I ran an experiment in which I got 6 different orders of size and now I'm trying to see if my observations are significant. I have to perform a MC simulation to get a p value to see if my observed values are unusually large or small compared to the null.
I need to:
I should have 6 new numbers, one for each bin, that add up to 20, but my output is saying 0. Im new to python so what am I doing wrong?
My code is here:
from random import randint
from random import seed
# seed random number generator
seed(1)
counter = 0
chi_sq_values = []
# want 10,000 simulations
while counter < 10000:
# will eventually mimic your real six orders of size
sim_orders = [0, 0, 0, 0, 0, 0]
# generating 20 random numbers
for i in range(20):
numbers = randint(0, 1)
if 0 <= numbers <= 1 / 6:
numbers += sim_orders[0]
if 1 / 6 <= numbers <= 2 / 6:
numbers += sim_orders[1]
if 2 / 6 <= numbers <= 3 / 6:
numbers += sim_orders[2]
if 3 / 6 <= numbers <= 4 / 6:
numbers += sim_orders[3]
if 4 / 6 <= numbers <= 5 / 6:
numbers += sim_orders[4]
if 5 / 6 <= numbers <= 6 / 6:
numbers += sim_orders[5]
print(sim_orders)
You're not incrementing the values in sim_orders
. You're adding the value in sim_orders
to numbers
, which has no effect because the value is always 0
. And then you're not doing anything with numbers
after you add to it.
You should increment the appropriate counter in sim_orders
.
You need to use random.random()
, not random.randint(0, 1)
. The latter will just return 0
or 1
, not a number between 0 and 1.
for i in range(20):
numbers = random.random()
if numbers <= 1 / 6:
sim_orders[0] += 1
elif numbers <= 2 / 6:
sim_orders[1] += 1
elif numbers <= 3 / 6:
sim_orders[2] += 1
elif numbers <= 4 / 6:
sim_orders[3] += 1
elif numbers <= 5 / 6:
sim_orders[4] += 1
else:
sim_orders[5] += 1
You should also use elif
for a sequence of mutually exclusive conditions, to avoid unnecessary tests. And if you do this, you don't need to test both ends of the range, since the previous test precludes numbers lower than the bottom of the range.
Your conditions overlapped -- if numbers
was an exact multiple of 1/6
it would be put into both bins.
You can also get rid of all the if
statements entirely:
sim_orders[floor(numbers*6)] += 1