Monte Carlo模拟N个骰子
Monte Carlo simulation of N dice
我正在做这个作业:
You are tossing N
dice. Write a program in Python that computes the probability that the sum is larger than 3N/2
and smaller than 9N/2
.
我认为我只有 3 个骰子,因为用 N
骰子做起来有点复杂,我已经尝试了一些,但我不明白如何找到 [=16] 的概率=]
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
我修正了第一个答案...不知道是否正确...
刚刚修复了明显的错误...
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
我正在做这个作业:
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
.
我认为我只有 3 个骰子,因为用 N
骰子做起来有点复杂,我已经尝试了一些,但我不明白如何找到 [=16] 的概率=]
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
我修正了第一个答案...不知道是否正确... 刚刚修复了明显的错误...
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