0

I have a question to deal with it in java.

My code has three variables: a,b,c respectively, all doubles. The sum of all variables must be equal 1.

I need to test all the possible combinations in these variables, with values varying from 0.10

Example:

Combination 1:

a = 0.20
b = 0.20
c = 0.60

Combination 2:

a = 0.10
b = 0.10
c = 0.80

and so go on.

Is there any framework or lib to automatize this kind of test?

gsjunior86
  • 73
  • 1
  • 5
  • 2
    On a side note, are you using BigDecimal or another arbitrary precision construct to store your values? 0.10, for instance, cannot be stored exactly with a `float` or `double`. – michaelgulak Oct 13 '14 at 16:54
  • You just need a nested for loop to generate them. An if-statement to do the check, so why go as far as getting a library to do it? – Fermat's Little Student Oct 13 '14 at 16:56
  • 1
    I dont know any lib for that but what about assigning a random number between 0 to 1 for a and another random between 0 and 1-a for b and then c will be 1-a-b? – CIsForCookies Oct 13 '14 at 16:57

1 Answers1

0

While another commenter pointed out that this can be accomplished with a 3-deep nested for loop, there might be a more elegant solution, perhaps using a library like combinatoricslib. You could then do this:

    ICombinatoricsVector<BigDecimal> originalVector = 
            Factory.createVector(new BigDecimal[] { 
                    new BigDecimal("0.0"), 
                    new BigDecimal("0.1"), 
                    new BigDecimal("0.2"), 
                    new BigDecimal("0.3"), 
                    new BigDecimal("0.4"), 
                    new BigDecimal("0.5"), 
                    new BigDecimal("0.6"), 
                    new BigDecimal("0.7"), 
                    new BigDecimal("0.8"), 
                    new BigDecimal("0.9")
    });

    Generator<BigDecimal> gen = Factory.createPermutationWithRepetitionGenerator(originalVector, 3);

    for (ICombinatoricsVector<BigDecimal> perm : gen) {
        // values are in perm.getValue(0), perm.getValue(1), and perm.getValue(2)
    }

Afterward, you could iterate through each permutation and check the sum with a for loop of depth 1.

Note that I have replaced float/double with BigDecimal in order to address floating point precision/representation issues. Further note that I have used the String constructor of BigDecimal to avoid an insipid form of the same precision/representation issues.

Community
  • 1
  • 1
michaelgulak
  • 631
  • 1
  • 6
  • 14