John Sall
John Sall

Reputation: 1139

How to generate a random normal distribution with specific standard deviation

I have already used this function :

np.random.seed(40)
np.random.normal(loc = 0, scale = 1, size = 10)

However, I'm assuming the values should be between 1 and -1 right? But I'm getting values that are larger than 1 and smaller than -1. How is that possible?

I'm getting this array :

array([-0.6075477 , -0.12613641, -0.68460636,  0.92871475, -1.84440103,
       -0.46700242,  2.29249034,  0.48881005,  0.71026699,  1.05553444])

You can see there're values like 2.2924 and also -1.8 which is ranges outside the standard deviation

Possible solution

I have made this code, is this okay?

final_data = []
count = 0
a = 26 # standard deviation
b = 157 # mean

for i in range(2000):
    y = a*np.random.normal(0, 1, 1) + b # equation to multiply by the std and add the mean
    if y <= upper and y >= lower :
        final_data.append(y[0])
        count += 1
        if count > 608:
            break;

Where upper and lower are the mean + std and mean - std. I have first generated a randomly distributed number and then put it in the equation. If the number is between the specific range, then I added it to the list

Upvotes: 0

Views: 4400

Answers (2)

doeeehunt
doeeehunt

Reputation: 33

Just to add to the previous comment and answer:

If you want to draw random numbers from an interval, you must choose a distribution with an upper and lower bound. For example, the uniform distribution puts equal probability on every number between an upper and lower bound. For numpy, you can check it out here: https://docs.scipy.org/doc/numpy-1.15.0/reference/generated/numpy.random.uniform.html

Upvotes: 1

Mohit S
Mohit S

Reputation: 46

Normal Distribution does not restrict the range of the values. It just means that 68% of the values will be within 1 standard deviation of the mean; 95% within 2 standard deviation and 99.7% within 3 standard deviations. Theoretically you could get any value from - infinty to infinity irrespective of your standard deviation.

Upvotes: 3

Related Questions