python - 如何生成总和为 1 的三个变量的所有可能组合
问题描述
我需要解方程 x + y + z = 1。
我需要生成 x、y、z 的所有可能组合,所以方程是正确的
我希望 x、y、z 的值介于 0.1 和 0.9 之间,跳跃为 0.1。
所以值被限制为 [0.1, 0.2, ..., 0.8, 0.9]
我找到了这个答案找到多个变量的所有组合总和为 1
但是它适用于 R 而不是 python。
如果有人能启发我,那将非常有帮助。
解决方案
Instead of a nested triple loop, you can consider generating all triplets
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)]
where each triplet (a,b,c)
represents the possible values to be assigned to x, y
, and z
.
Note that I'm multiplying by 10 for then dividing when building the triplets to avoid rounding errors that might come up when doing directly:
if x/10 + y/10 + z/10 == 1:
推荐阅读
- c# - 在 Blazor 中验证复杂类型模型中的单个字段
- java - 为什么Java中出现错误的问候
- javascript - 将数组中的值分配给javascript中的变量
- traffic - 谷歌地图信息提取
- tensorflow - AttributeError:“张量”对象没有属性“SerializeToString”
- bitbucket - git push auth fail after setting remote origin to bitbucket
- timestamp - KeyError: Timestamp('2019-12-23 23:59:58.142906')
- php - codigniter 将多个值插入数据库不起作用
- timer - RESET timer after each match
- java - 在 c# 到 Java 中是否有与 Marshal 等价的东西?