'python random_sample to generate values

I am currently using random_sample to generate weightage allocation for 3 stocks where each row values add up to 1 and I rounded them to 2dp.

weightage=[]
n = 0
while n < 100000:
    weights = np.random.random_sample(3)
    weights  = weights/ np.sum(weights)
    weights = (np.around(weights,2))
    if any(i < 0.05 for i in weights):
        continue
    n += 1
    weightage.append(weights)
    
weightage

However there are some weightage allocations that exceed 1 as shown below. Possibily due to rounding up the values.

 array([0.74, 0.15, 0.12])

Is there any way to have my allocations in 2 decimal places without exceeding 1?



Solution 1:[1]

Try truncating in line 7 instead of rounding:

import numpy as np
weightage=[]
n = 0
while n < 10:
    weights = np.random.random_sample(3)
    weights  = weights/ np.sum(weights)
    weights = weights // 0.01 / 100
    if any(i < 0.05 for i in weights):
        continue
    n += 1
    weightage.append(weights)

print(weightage)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gerald