0

I am trying to generate all possible combinations under some constraints using the python-constraint. Here are the main() code:

list1 = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2.0]

list2 = [-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]

list3 = [-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0]

problem = constraint.Problem()

problem.addVariable('p1', list1)
problem.addVariable('p2', list2)
problem.addVariable('p3', list3)

problem.addConstraint(our_constraint, ['p1', 'p2', 'p3'])
solutions = problem.getSolutions()

The three lists are constrained within specific range. The function, our_constraint, is defined by:

def our_constraint(p1, p2, p3):
  if (p1 + p3 + p2) == 0:
    return True

However, the output I get does not include every possible combinations. Some data are shown in below:

{'p3': -1.0, 'p1': 2.0, 'p2': -1.0}
{'p3': -1.0, 'p1': 1.8, 'p2': -0.8}
{'p3': -1.0, 'p1': 1.7, 'p2': -0.7}
{'p3': -1.0, 'p1': 1.6, 'p2': -0.6}
{'p3': -1.0, 'p1': 1.5, 'p2': -0.5}
{'p3': -1.0, 'p1': 1.3, 'p2': -0.3}
{'p3': -1.0, 'p1': 1.2, 'p2': -0.2}
{'p3': -1.0, 'p1': 1.1, 'p2': -0.1}

It does not include combinations like

{'p3': -1.0, 'p1': 1.4, 'p2': -0.4}

{'p3': -1.0, 'p1': 1.9, 'p2': -0.9}

I tried to rearrange the order of p1, p2 and p3 in our_constraint. And I found that it will generate other combinations. Why is that? And how can I fix it?

CDJB
  • 14,043
  • 5
  • 29
  • 55
JJT
  • 1
  • 3
    See https://stackoverflow.com/questions/588004/is-floating-point-math-broken – JohanC Feb 14 '20 at 13:02
  • Welcome to StackOverflow. Agreed, @JohanC. Please see https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html . – rajah9 Feb 14 '20 at 13:06
  • By the way, when asking a question, it is very helpful to include all of your import statements. For your question, "from constraint import *" is critical. And a separate "pip install python-constraint" wouldn't hurt either, since this is not a part of the standard Python library. – rajah9 Feb 14 '20 at 13:08

0 Answers0