Reputation: 427
I'm doing this assignment:
You are tossing
N
dice. Write a program in Python that computes the probability that the sum is larger than3N/2
and smaller than9N/2
.
I supposed that I have only 3 dice because it's a little bit complicated to make with N
dice and I've tried something but I don't understand how to find the probability that the 9N/2 > sum > 3N/2
import random
num_throws = 20 # NT
roll_log = [0] * 12 # Generate list for dice roll tallies
for i in range(num_throws):
# Random integer between 1 and 6 inclusive for each dice
dice_1 = random.randint(1, 6)
dice_2 = random.randint(1, 6)
dice_3 = random.randint(1, 6)
# Sum the random dice and increment the tally for that particular roll total
roll_sum = dice_1 + dice_2
roll_log[roll_sum-1] += 1 # minus 1 because Python is 0-indexed
for i, tally in enumerate(roll_log):
roll_prob = float(tally) / num_throws # Experimental probability of roll
roll = i + 1 # Since Python lists are 0-indexed
print('{}: {}/{} = {}'.format(roll, tally, num_throws, roll_prob))
n = 5
m = 10
rolls_between = roll_log[n:m-1]
sum_rolls_between = sum(rolls_between)
prob_between = float(sum_rolls_between) / num_throws
Upvotes: 1
Views: 509
Reputation: 1187
I fixed the first answer... no idea if correct... Just fixed the obvious errors...
import random
N = 3
NUM_ROLLS = 10000
UPPER_BOUND = 9 * N / 2
LOWER_BOUND = 3 * N / 2
counter = 0
for _ in range(NUM_ROLLS):
s = sum([random.randint(1, 6) for _ in range(N)])
if s < UPPER_BOUND and s > LOWER_BOUND:
counter += 1
prob = 1.0 * counter / NUM_ROLLS
print "Upper Bound = ", UPPER_BOUND
print "Lower Bound = ", LOWER_BOUND
print prob
Upvotes: 0