Week 18 Exercise

Hi all, Anybody please give the code of rolling of dice and plotting the n vs variance .I tried but now completely lost.

I have it but need some review, will share it today

1 Like

import numpy as np

import pandas as pd

import seaborn as sns

sum = 0

rd = np.arange(1,7)

ar = np.float64()

avg = 0

for i in rd:

ar = np.append(ar, i)

sum = sum + i

ar = np.delete(ar, [0], axis=0)

#avg

avg = sum/len(rd)

print(“Average:”, avg)

print(ar)

#(mean - x)

#ar1 = np.array([0], dtype=np.float64)

ar1 = ar - avg

print(ar1)

#ar**2

ar1 = ar1 * ar1

print(ar1)

#var

print(“variance”, ar1/(len(rd-1)))

#draw the graph between n and var

sns.barplot(x=rd, y=ar1/(len(rd-1)))

#Above code works need to clean up/upgrade needed for optimization.

1 Like

#Following n dices and samples with n size of each sample,

#You need to keep in matrix to work on that, pls change the values n and count it works reasably till #50, more then that it takes some good time i did not try. Do not try huge values.

#Normal distribution - graph with dices

import numpy as np

import pandas as pd

import seaborn as sns

ar = np.linspace(1, 6, 6).astype(int)

#no of dices

n = 25

ar = np.arange(0,1)

ar = np.delete(ar,(0,0), axis=0)

for i in range(1, n+1):

ar = np.append(ar, np.arange(1,7), axis=0)

print(ar)

ar = np.reshape(ar, (n,6)).astype(float)

print(ar)

print(“Array Dime Size:”, ar.ndim)

#samples(n-1) and size of each sample is n.

count = 50

#dim1 = np.random.randint(0,n, size=count)

dim2 = np.random.randint(0,6, size=count)

#print(“Dim1:”, dim1)

print(“Dim2:”, dim2)

p = {}

sum = 0

t = 0

week19 = np.array(0)

week19 = np.delete(week19, 0)

n_samples = np.array(0)

n_samples = np.delete(n_samples, 0)

sum_sam = 0

#sum them up samples for each count

for i in range(count):

for d2 in dim2:

sum = 0 dim1 = np.random.randint(0,n, size=count) #print(“d2 -> Dim1:”, d2, “->”, dim1) for d1 in dim1: t +=ar[d1, d2] sum = sum + ar[d1,d2] week19 = np.append(week19, ar\[d1,d2\]) if (sum in p): p\[sum\] = p\[sum\] + 1 else: p\[sum\] = 1

sum_sam = sum_sam + t

n_samples = np.append(n_samples, sum_sam)

sum_dices = t

print(“Total sum:”, np.sum(week19))

print(“Total avg”, np.average(week19))

#Find P(X) = x

print(“Prob of dices”, p)

#This is prob

s = pd.Series(p.values(), index=p.keys())

s = s / 6 ** (n)

print(s)

#sns.barplot(s, y=s.values)

#print(df)

#This is var for each value

week19 = week19 - np.average(week19)

week19_1 = week19 * week19

#var for each val

sns.barplot(x=week19, y=week19_1/(len(week19) - 1))

1 Like