https://www.hackerrank.com/challenges/s10-normal-distribution-1
In this challenge, we learn about normal distributions. Check out the Tutorial tab for learning materials!
In a certain plant, the time taken to assemble a car is a random variable, X, having a normal distribution with a mean of 20 hours and a standard deviation of 2 hours. What is the probability that a car can be assembled at this plant in:
Less than 19.5 hours?
Between 20 and 22 hours?
There are lines of input (shown below):
20 2
19.5
20 22
The first line contains 2 space-separated values denoting the respective mean and standard deviation for X. The second line contains the number associated with question 1. The third line contains 2 space-separated values describing the respective lower and upper range boundaries for question 2.
If you do not wish to read this information from stdin, you can hard-code it into your program.
In [7]:
import math
from matplotlib import pylab as plt
%matplotlib inline
In [8]:
def pdf(x, m, variance):
sigma = math.sqrt(variance)
"""probability density function"""
return 1 / (sigma * math.sqrt(2 * math.pi)) * math.e ** (-1 * ((x - m)**2 / (2 * variance ** 2)))
In [26]:
pdf(20, 20, 4)
Out[26]:
In [28]:
N = range(50)
mean = 15
variance = 3
plt.plot(N, [pdf(i, mean, variance) for i in N])
Out[28]:
In [79]:
def cumulative(x, m, stdv):
return 0.5 * (1 + math.erf((x-m)/ (stdv * math.sqrt(2)) ))
In [56]:
[(i, cumulative(i, 20.0, 3.0)) for i in range(1, 30)]
Out[56]:
In [58]:
mean = 20
variance = 4
In [80]:
x = 19.5
q1_answer = cumulative(x, mean, math.sqrt(variance))
q1_answer
Out[80]:
In [81]:
lower_hour, upper_hour = 20.0, 22.0
q2_answer = cumulative(upper_hour, mean, math.sqrt(variance)) - cumulative(lower_hour, mean, math.sqrt(variance))
q2_answer
Out[81]:
In [ ]: