Search code examples
pythonmontecarlostandard-deviation

Monte Carlo standard deviation python


Hello I tried to solve a problem in python with the Monte Carlo method. The problem is the following: A company services notebooks. A review of its records shows that the time taken for a service call is normally distributed with a mean of 60 minutes and standard deviation of 20 minutes. a. What proportion of service calls take less than one hour? b. What proportion of service calls take more than 50 minutes? c. What proportion of service calls take more than 80 minutes? d. If a service call has taken more than an hour, what is the probability that it will take more than 70 minutes? d. In a random sample of four calls, what is the probability that the average length of calls is less than one 50 minutes?

My solution for this:

import math
import random
calls = 4
sa = 0
sb = 0
sc = 0
sd = 0
sd2 = 0
se = 0
sumMin = 0
for i in range (1,calls):
    r = 60 + 20.* random.randint(1, calls)
    #print(r)
    if r<60:
        sa = sa + 1
        break
    if r > 50:
        sb = sb + 1
        break

    if r > 80:
        sc = sc + 1
        break

    if r > 60:
        sd2 = sd2 + 1
        break

    if r > 60:
        sd = sd + 1
        break
    break
sumMin = sumMin + r
meanCallsl = sumMin / calls
if meanCallsl < 50:
    se = se + 1

and for a,b,c,d the following conditions

pa = 100 * sa/ calls
print (pa)

pb = 100 * sb / calls
print(sb)

pc = 100 * sd / calls
print(pc)

pd = 100*sd/sd2
print (pd)

pe = 100 * se/calls
print(pe)

Though I am not sure of the outcome, could you please advise?

Thank you


Solution

  • Firstly, if you want advice on stack overflow, you should really explain what makes you doubt your code. The fact that you only get 0 and 1 should be in your main post. This is because you should not write break in your code.

    I assume you've programmed in MATLAB before, where you need to write end to end your for loop and if tests. In python, this is not necessary, as the indentation of your code define the code blocks of your for loop and if tests.

    Furthermore, you are never testing for 70 minutes in your code. I assume you want to do that to answer question d.

    Moreover, why do you have the code random.randint(1, calls)? The Python documentation says that

    random.randint(a, b)

    Return a random integer N such that a <= N <= b. Alias for randrange(a, b+1).

    which means that your random.randint(1, calls) will produce a random integer between 1 and calls inclusive. random.gauss is probably the function that you are interested in (see https://docs.python.org/3/library/random.html#random.gauss for documentation).