Maryam
Maryam

Reputation: 159

Random list with specific length and sum

I need a list of random floats with a sum of 1 and a certain length.

To my knowledge, the methods I have seen generate all possible scenarios, and it is possible that there are no lists with a specific length among the cases. Although making the remaining elements of the list equal to zero is an option, it doesn't seem like a good idea!

It is costly and time-consuming to just make this list by trial and error, so the program is time-consuming.

Upvotes: 0

Views: 234

Answers (1)

Pierre D
Pierre D

Reputation: 26201

Try:

import numpy as np

n = 100
a = np.random.normal(size=n)
a /= a.sum()

After that:

>>> a.sum()
0.9999999999999998

Note: if your list is short and you are worried of the absolutely exceptional case where the initial a.sum() be 0, then:

while True:
    a = np.random.normal(size=n)
    if not np.allclose(a.sum(), 0):
        a /= a.sum()
        break

Upvotes: 1

Related Questions