0
pop = 100
number = list(range(pop+1))
comb = [c for c in itertools.product(number, repeat=3) if  c[0] + c[1] + c[2] == pop]

This code generate all the triple of integer number that sum up to 100. I loop and check it, and it is fine. But than if I divide each tuple by 100 they do not sum to 1.0, but some entries sum to 0.99999999 or 1.00000002

poss_states = []
for i in range(len(comb)):
      poss_states.append(np.divide(np.array(comb[i]),100))

To check if they sum to 1.0 I used:

for i in np.array(poss_states).sum(axis=1):
    if i != 1.:
        print(i)

I tried several ways to normalize but nothing works. How could I force the sum to be 1.0?

  • 3
    Floats are inexact and arithmetic operations with them have inexact results. Why do you want to calculate with the floats instead of the integers and just remember that the ints are percentage values? And by the way: Repair the formatting of your code. – Michael Butscher May 16 '20 at 12:18
  • 1
    This seems like the question of [Is Floating Point Math Broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken), which basically means we don't expect to get precise results when summing floating point numbers. As an aside I'm not sure why you add numpy operations unnecessarily. For instance, rather than `number = list(np.array(range(pop+1)))`, you could just have `number = range(pop+1)`. – DarrylG May 16 '20 at 12:19
  • @MichaelButscher because at the end I want to use 300 or other values for pop. – Tommaso Iaquinta May 16 '20 at 12:35
  • @TommasoIaquinta You can do that already. The checking of all possible products would take longer then but when using floats it would take incredibly long. – Michael Butscher May 16 '20 at 13:58
  • @MichaelButscher if I use pop = 300 i get approximatively 45 thousand combination which sum all up to 300. But if I try to normalize, dividing by 300 I get the same problems. And I can not image as you suggest before that they're percentages. – Tommaso Iaquinta May 16 '20 at 14:11
  • You will always have these problems with normalization to floats. And you would have billions (or more) of combinations if you try to calculate them with floats. – Michael Butscher May 16 '20 at 14:37

0 Answers0