Reputation: 610
I want to create a random number generator but with condition.
code is like below;
s_weights = []
num = 3
limit = 50000
np.random.seed(101)
for x in range(limit):
weights = np.random.random(num)
weights /= np.sum(weights)
s_weights.append(weights)
it returns me 50.000 lists of numpy array of 3 weights (3,) like below
0.429134083359603413e-01 5.115615408184341906e-01 2.552505084560561729e-02
I want to limit first weight with rule of >=0.60
first weight should change between 0.60 - 1.00 and other two should change between 0.00 - 1.00
how can I modify the code?
thanks in advance
Upvotes: 1
Views: 1390
Reputation: 1270
You can scale the first weight and then generate the other weights to respect the restriction of summing to 1. The updated code is below:
import numpy as np
s_weights = []
num = 3
limit = 50000
np.random.seed(101)
offset = 0.6
for x in range(limit):
# By default all the weights go from 0 to 1
weights = np.random.random(num)
# shift and scale the first one to go from 0.6 to 1
# in the case offset is 0.6 then it is x*0.4 + 0.6, which for 0 in 0 to 1 always falls in 0.6 to 1
weights[0] = weights[0]*(1-offset) + offset
# Scales the second weight respecting that the sum must be 1
second_max = 1-weights[0]
weights[1] = weights[1]*second_max
# third component should be equal to the value we need to complete 1
weights[2] = 1-weights[0]-weights[1]
s_weights.append(weights)
print(weights)
print(sum(weights))
an example output of a set of weights their sum is below
[0.84739308 0.11863514 0.03397177]
1.0
Upvotes: 1