您可以一个一个地生成数字,在每一步计算您已经获得的权重的总和。我将使用 random.randint 函数进行演示。
import random
weights_name = ["Multi", "Equity 1", "Equity 2", "Equity 3", "FI", "Cash"]
weights = [0] * 6
weights[1] = 0.15 # Equity 1 weight
remaining = 0.85 # the sum of the remaining weights
x = random.randint(0, 100)
weights[-1] = x/1000 # Cash weigth
remaining -= weights[-1]
因此,对于剩余的权重,您必须生成随机值,以使最后一个不会大于 0.2。
last_weight = remaining
while last_weight > 0.2:
last_weight = remaining
for i in [0, 2, 3]:
weights[i] = 0.05 + random.randint(0, 150)/1000 # generating a random no between 0.05 and 0.20
last_weight -= weights[i]
weights[4] = last_weight
for w in weights:
print(w)
我的输出:
0.2
0.15
0.176
0.196
0.18200000000000005
0.096