【问题标题】:Python: Create a list (at N length) of all possible proportions of 1 incremented by d decimal pointsPython:创建一个列表(长度为 N),其中 1 的所有可能比例增加了 d 个小数点
【发布时间】:2015-11-24 22:04:09
【问题描述】:

我想制作一个长度为N 的浮点数列表,其总和始终为1,每个浮点数递增d 数量。

例如,让N = 4 和d = 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,但使用随机数而不是所有可能的组合。

【问题讨论】:

  • “并且每个浮点数增加 d 数量”我不清楚。你是说d 是最大小数位数吗?

标签: python


【解决方案1】:

我认为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

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

浮点数是浮点数,你会得到一些浮点错误,你可以在嵌套列表理解中使用适当的round 来控制。

【讨论】:

    猜你喜欢
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 2022-12-04
    • 1970-01-01
    相关资源
    最近更新 更多