In: Computer Science
Directly using mathematical expression, DO NOT USE the built-in Python functions, evaluate the binomial function for n = 20, p = 3/8. Make sure you plot your results (Remember the the binomial distribution is discrete)
import math
import numpy as np
import matplotlib.pyplot as plt
# function to calculate binomial co-efficient
def NchooseK(n, k):
a = math.factorial(n)
b = math.factorial(k)
c = math.factorial(n - k)
ret = a/(b * c)
return ret
def PB(x, n, p):
ans = (NchooseK(n, x))*(p**x)*((1-p)**(n-x))
return ans
n = 20
xx = [] # initialise array to save x values from 0 to 8
yy = [] # initialise array to save PB(x,n,p) values for p = 0.5
p = 0.375
# save PB(x,n,p) values for p = 0.375
for x in range(0, 21):
tmp = PB(x, n, p)
xx.append(x)
yy.append(tmp)
print("n = ", n, " p = ", p, " x = ", x, " PB(x, n, p) = ", tmp)
# plot the data
plt.plot(xx, yy, color="red", label='PB(x,n,p) for p = 0.375')
plt.xlabel('x')
plt.legend(loc='upper right')
plt.show()
PLEASE LIKE IT RAISE YOUR THUMBS UP
IF YOU ARE HAVING ANY DOUBT FEEL FREE TO ASK IN COMMENT
SECTION