gpt4 book ai didi

Python:创建一个列表(长度为 N),其中包含 1 的所有可能比例,增加 d 个小数点

转载 作者:行者123 更新时间:2023-12-01 04:31:43 30 4
gpt4 key购买 nike

我想创建一个 N 长度的 float 列表,其总和始终为 1,并且每个 float 递增 d 数量。

例如,让 N = 4d = 0.01:

期望的结果是这样的:

[0.90, 0.02, 0.03, 0.05]
[0.89, 0.02, 0.03, 0.06]
....
# And continues until all possible sums of 1 with the above settings is reached.
# An individual value CAN NOT = 0

我正在尝试为此思考一些逻辑,但我需要一些帮助。之前我问过question性质相似,但使用随机数而不是所有可能的组合。

最佳答案

我认为 itertools 让这变得非常简单:

from itertools import permutations, ifilter

N = 4
d = 0.01
D = int(1/d)


perms = ifilter(lambda x: sum(x) < D, permutations(range(1,D-1), N-1))
tuples = []
for i in perms:
tuples.append(i + (D-sum(i),))

mylist = [ [ i*d for i in eachtuple ] for eachtuple in tuples ]

print mylist

我假设对于某个整数nd 将为 10^(-n),但这适用于任何具有整数倒数的东西(0.05 和 0.2 应该有效,但不是 0.03)。

float 是 float ,你会得到一些浮点错误,你可以通过嵌套列表理解中适当的round来控制这些错误。

关于Python:创建一个列表(长度为 N),其中包含 1 的所有可能比例,增加 d 个小数点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32301616/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com