you will simulate rolling ?n dies and recording their sum. For example, if n=2 and the first die shows up as a 3, and the second die shows up as a 1, the sum (and the value we record) would be 4.
TO DO: Complete the two function stubs below and then demonstrate by providing code which would print out the probability distribution for rolling 2 dice 100,000 times.
seed(0)
def roll_and_add_dice(num_dice, num_trials =
10**6):
pass # Your code here
show_distribution(roll_and_add_dice(2),title='Probability Distribution for Sum of Two Dice')
PYTHON CODE:
import matplotlib.pyplot as plt import random def roll_and_add_dice(num_dice, num_trials = 10**6): dict={} for i in range(num_dice,6*num_dice+1): dict[i]=0 for i in range(0,num_trials): sum=0 for j in range(0,num_dice): sum+=random.randint(1,6) dict[sum]+=1 return dict def show_distribution(vectors,title): x=list(vectors.keys()) y=list(vectors.values()) plt.plot(x,y) plt.title(title) plt.show() show_distribution(roll_and_add_dice(2),title='Probability Distribution for Sum of Two Dice')
Output plot:
Get Answers For Free
Most questions answered within 1 hours.