【问题标题】:How to generate all the possible combinations of three variables that sum to 1如何生成总和为 1 的三个变量的所有可能组合
【发布时间】:2020-01-12 06:30:01
【问题描述】:

我需要解方程 x + y + z = 1。

我需要生成 x、y、z 的所有可能组合,所以等式是正确的

我希望 x、y、z 的值在 0.1 和 0.9 之间,跳跃为 0.1。

所以值被限制为 [0.1, 0.2, ..., 0.8, 0.9]

我找到了这个答案Finding all combinations of multiple variables summing to 1

但它适用于 R 而不是 python。

如果有人能启发我,那将非常有帮助。

【问题讨论】:

  • I need to generate all the possible combinations of x, y, z so the equation is correct. xyz 的域是什么?
  • 是3D空间中的平面x+y+z=1。它是通过 (0,0,1)、(0,1,0) 和 (1,0,0) 的唯一平面。
  • 你不能生成所有的值,因为它们有无数个。
  • 没有更多的限制,有无限的解决方案。请更新您的问题以指明您要查找的问题。
  • 我已经添加了限制。我希望值在 0.1 和 0.9 之间,跳跃为 0.1。

标签: python


【解决方案1】:

可以考虑生成所有三元组,而不是嵌套的三元组

triplets = [(x/10.0, y/10.0, (10-x-y)/10.0) for x in range(1,9) for y in range(1,10-x)]

其中每个三元组(a,b,c) 表示要分配给x, yz 的可能值。

请注意,在构建三元组时,我乘以 10 然后除以避免直接执行时可能出现的舍入错误:

if x/10 + y/10 + z/10 == 1:

【讨论】:

    【解决方案2】:

    最原始的解决方案是所有组合的嵌套循环:

    def variable_combinations(sum_up_to=1):
        for x in range(1, 10):
            for y in range(1, 10):
                for z in range(1, 10):
                    if x/10 + y/10 + z/10 == sum_up_to:
                        yield (x/10, y/10, z/10)
    
    all_solutions = list(variable_combinations())
    

    【讨论】:

      【解决方案3】:

      在python中直接避免嵌套循环:

      import itertools
      import numpy as np
      x = y = z = [ i/10 for i in range(1,10)]
      
      p = itertools.product(x,y,z)
      combs = [e for e in p if np.sum(e) == 1]
      

      现在combs 是总和为 1 的三元组(元组)列表。

      【讨论】:

        猜你喜欢
        • 2018-03-31
        • 1970-01-01
        • 2023-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多