0

I need to solve the equation x + y + z = 1.

I need to generate all the possible combinations of x, y, z so the equation is correct

I want the values of x, y, z to be between 0.1 and 0.9 with jump of 0.1.

So the values are restricted to [0.1, 0.2, ..., 0.8, 0.9]

I have found this answer Finding all combinations of multiple variables summing to 1

However it applies to R not python.

It would be very helpfull if someone would enlighten me.

Djboboch
  • 45
  • 1
  • 6

3 Answers3

2

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:
abc
  • 11,579
  • 2
  • 26
  • 51
0

The most primitive solution would be a nested loop over all combinations:

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())
L3viathan
  • 26,748
  • 2
  • 58
  • 81
0

Avoiding nested loops directly in 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]

Now combs is a list of triplets (tuples) that sum to 1.

FBruzzesi
  • 6,385
  • 3
  • 15
  • 37