Given k a random integer between 2 and 7. How to generate a list of k positive numbers whose sum is equal to 1?
Examples of possible expected results:
k = 3 -> list = [0.23, 0.57, 0.2]
k = 3 -> list = [0.41, 0.44, 0.15]
K = 2 -> list = [0.95, 0.5]
CodePudding user response:
You can generate k random numbers (for example in the range 0-1), then divide by their sum.
Example with numpy
(for efficiency):
k = 3
import numpy as np
a = np.random.random(k)
out = (a/a.sum()).tolist()
pure python:
k = 3
import random
l = [random.random() for _ in range(k)]
s = sum(l)
out = [e/s for e in l]
example: [0.27830153962545046, 0.19826407925979248, 0.523434381114757]
CodePudding user response:
I hope you are well.
you can use this code to do this:
import numpy as np
def softmax(x):
res = np.exp(x - np.max(x))
return res / res.sum()
size=5
list=np.random.random(size)
list=softmax(list)
CodePudding user response:
Using a infinite loop which break once get all k
numbers. Repeated numbers may occurs.
import random
#random.seed(3) # for testing purposes
k = 5
partition_of_unit = []
while True:
if len(partition_of_unit) == k-1:
break
n = random.random()
if sum(partition_of_unit) n < 1:
partition_of_unit.append(n)
partition_of_unit.append(1-sum(partition_of_unit))
print(partition_of_unit)
#[0.6229016948897019, 0.029005228283614737, 0.11320596465314436, 0.013114189588902203, 0.22177292258463677]
print(sum(partition_of_unit))
#1.0