2

I wants to check all combination values which satisfy the conditions given in if statement

def drange(start, stop, step):
    r = start
    while r < stop:
        yield r
        r += step   

for a in drange(0.1, 0.9,0.1):
    for b in drange(0.1, 0.9,0.1):
        for c in drange(0.1, 0.9,0.1):
            if a+b+c == 1 and a>b>c:
                print a
                print b
                print c

It is working but doesn't give the all combinations.

Upendra
  • 61
  • 7
  • There should be four combinations but it give only three combinations. It miss a=0.7 b=0.2 c=0.1 – Upendra Jan 02 '16 at 03:40
  • Or, in other words, why `print 0.7+0.2+0.1 == 1` returns `False` ? :) – Nir Alfasi Jan 02 '16 at 03:45
  • You could change `drange(0.1, 0.9, 0.1)` to `drange(1, 9, 1)` and compare `a+b+c = 10` as a workaround. When printing out information, do `print a/10.0` – zedfoxus Jan 02 '16 at 03:54

1 Answers1

4

What you’re running into here is essentially the problem behind floating point alrithmetic. See this question for further information about what’s going on and why it happens.

To sum it up, just look at the results from your drange(0.1, 0.9, 0.1):

>>> list(drange(0.1, 0.9, 0.1))
[0.1, 0.2, 0.30000000000000004, 0.4, 0.5, 0.6, 0.7, 0.7999999999999999, 0.8999999999999999]

As you can see, you don’t get exact results there. So when you sum them up, you won’t get an exact 1.

Instead, when comparing floats with rounded numbers, you should always allow for some kind of precision loss. One way to do that is to take the difference and see if it’s below some threshold (in this case, I chose 0.00001):

if abs((a + b + c) - 1) < 0.00001:
    print('The sum is likely 1')

So in your case, your code could look like this:

for a in drange(0.1, 0.9, 0.1):
    for b in drange(0.1, 0.9, 0.1):
        for c in drange(0.1, 0.9, 0.1):
            if abs((a + b + c) - 1) < 0.00001 and a > b > c:
                print a
                print b
                print c

And that will safely produce the expected output.

Community
  • 1
  • 1
poke
  • 369,085
  • 72
  • 557
  • 602
  • Thank you very much for your answer. It is working properly and I got understand the reason. – Upendra Jan 02 '16 at 03:49
  • @Upendra Glad it is working for you. Please remember to [accept the answer](http://meta.stackexchange.com/a/5235/141542) if it solved your problem to mark this question as resolved. – poke Jan 02 '16 at 16:26