python random_sample to generate values



我目前使用random_sample为3只股票生成权重分配,其中每行值相加为1,并将其四舍五入为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

但是,有一些权重分配超过1,如下所示。可能是由于四舍五入的值。

array([0.74, 0.15, 0.12])

是否有办法使我的分配在小数点后2位而不超过1?

尝试截断第7行,而不是四舍五入:

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)

最新更新