generate random decimal numbers from 0 to 1 with normal distribution using numpy

Question:

I am new to numpy. I want to generate random values from 0 to 1 with random distribution using numpy, the known input is the standard deviation = 0.2 and the Mean = 0.55 and no. of population = 1000. I used this code:

number = np.random.normal(avg, std_dev, num_pop).round(2)

However it generated number with negative values and also values greater than 1. How to limit the value from 0 to 1?

Asked By: Sara Lee

||

Answers:

You can use

number = numpy.random.rand(1).round(2)

It will generate a random number in interval [0,1).

Answered By: Rahul Chauhan

The normal distribution has no lower or upper bound, and sampling from it and discarding the results outside your bounds until you get the 1000 necessary points would be awkward.
Luckily there’s the truncated normal distribution:

from scipy import stats

low = 0
high = 1
mean = 0.55
stddev = 0.2
num_pop = 1000

number = stats.truncnorm.rvs(low, high,
                             loc = mean, scale = stddev,
                             size = num_pop)
Answered By: BatWannaBe

I faced the same issue. Here’s what I used to resolve it:

number = abs(np.random.normal(0,1,1))
if number > 1:
    number = number - 1

abs finds the absolute value of number, making it positive.

The if statement at the end makes sure the number does not go over one, because we are using a normal distribution which does not have an upper or lower limit.

Hope this helped!

Answered By: Astro648
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.