簡體   English   中英

使用 itertools 獲取所有加起來為 1 的可能組合

[英]get all possible combinations that add up to 1 using itertools

我想創建一個包含 3 個元素(0.05 增量)的列表列表,它們加起來為 1,即 [[0,0,1],[0,0.05,0.95],[0,0.1,0.9],[0 ,0.15,0.85]...[0.95,0.05,0],[1,0,0]]。

這是我寫的代碼:

import itertools.product
possible_contributions = [i/100 for i in range(0,101,5)]
all_model_combs = itertools.product(possible_contributions, repeat=3)
usable_list = [comb for comb in all_model_combs if sum(comb)==1]

usable_list的長度為 226。我注意到我的usable_list中缺少幾種可能的組合,例如 [0.2,0.7,0.2]、[0.3,0.35,0.35]、[0.3,0.6,0.1]...我在失蹤者中找不到模式。 我發現很難解決itertools.product ,我想知道我錯過了什么/

這是浮點運算的限制。 使用 math.isclose() 並將可接受接近度的容差設置為 1,而不是等於 1:

import itertools
import math
possible_contributions = [i/100 for i in range(0,101,5)]
all_model_combs = itertools.product(possible_contributions, repeat=3)
usable_list = [comb for comb in all_model_combs if math.isclose(sum(comb),1, rel_tol=1e-06)]

print(len(usable_list)) #231

這是一個舍入錯誤,如果你用整數嘗試它可以工作:

import itertools
possible_contributions = [i for i in range(0,101,5)]
all_model_combs = itertools.product(possible_contributions, repeat=3)
usable_list = [comb for comb in all_model_combs if sum(comb)==100]
(20, 60, 20) in usable_list
(30, 35, 35) in usable_list
(30, 60, 10) in usable_list

但是30/100 + 35/100 + 35/100 != 100/100

我建議你

  • 僅在最后除以 100 或
  • 給您的總和比較更多空間,例如abs(sum(comb) - 1) < 0.0001

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM