Home > other >  Generate random numbers between [0,1] with shape of normal distribution
Generate random numbers between [0,1] with shape of normal distribution

Time:04-26

I want to generate 30 random numbers between [0,1] with the shape of normal distribution, Also I want their sum to be equal to 1.

CodePudding user response:

I don't exactly know what you mean by "shape of normal distribution" or "sum to be equal to 1" but you could try this:

from random import randint

numbers = []

for i in range(30):
    numbers.append(randint(0, 1))

print(numbers)

(My) Output:

[1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0]

It might not be the best or cleanest code but it works.

CodePudding user response:

Doesn't need numpy, you just need to import random and use random.uniform, but for larger code base you could do it like this:

import numpy

## step 1: generating a list of 29 pseudo random numbers between 0.0 and 1.0
array = numpy.random.random_sample(size=29)

## step 2: ensuring the sum of that list will not be higher than 1.0
while(sum(array) > 1.0):
    for i,a in enumerate(array):
        array[i] = a * 0.9

## step 3: appending the last number to the list such as the sum will be exactly 1.0
array = numpy.append(array, (1.0 - sum(array)))

print(f"the sum of elements is {sum(array)}")
print(f"the elements: {str(array)}")

What this does is generate an array of 29 random numbers between 0.0 and 1.0, which will obviously have a sum higher than 1.0 because the sum range is ~0.0-29.0.

The while loop will multiply every number for 0.9, making them closer to 0.0 and therefore lowering the sum until it's below 1.0

Then the last number is the difference between 1.0 and the current sum of the other 29 numbers, making it a total of 30 pseudo random numbers. The last one is as random as the other 29 because it is determined by all of them.

Gaussian algorithm implementation is left as an exercise to the reader.

  • Related