简体   繁体   中英

How can I create a array using the random function whose sum is 1 in python using nympy?

Working on an assignment which requires me to create an array with random numbers whose sum is 1.

The actual problem statement looks something like this:

get_initial_weights

This function should have one parameter, an integer m. This function should return a matrix with 1
row and m columns containing random values, each between zero and one. The sum of these m
values should be equal to one.

You can use random.random to create your matrix of size (1,m) , and then divide it by the sum of the array to normalize the sum to 1.

t = np.random.random((1,m))
t = t / t.sum()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM