gnak
gnak

Reputation: 11

Why do these two seemingly equivalent expressions evaluate differently?

Why do these two seemingly equivalent expressions evaluate differently? This works:

from random import uniform

def binominal_rv(n,p):
    z=[]
    counter=0
    for i in range(n):
        U=uniform(0,1)
        if  U < p :                #true with probability p
            counter= counter + 1
    return counter

But this does not:

from random import uniform

def binominal_rv(n,p):
    z=[]
    counter=0
    for i in range(n):
        U=uniform(0,1)
        if  U < p== True :                #true with probability p
            counter= counter + 1
    return counter

Whats going on here??? I think that the two if's should be equivalent.

Upvotes: 1

Views: 44

Answers (2)

Lambda Fairy
Lambda Fairy

Reputation: 14686

It's due to how Python reads expressions.

U < p == True is read as U < p and p == True. This is clearly not what we want.

As namit said, we can fix this using brackets: (U < p) == True. Or just use U < p, as in the original code.


If you want to learn more, the Python language reference explains this feature in detail:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).

Upvotes: 3

namit
namit

Reputation: 6957

change if U < p== True : to if (U < p)== True :

lets take an example:

In [38]: 2 < 4
Out[38]: True

In [39]: 2 < 4 == True
Out[39]: False

In [40]: (2 < 4) == True
Out[40]: True

In [41]: 4 == True
Out[41]: False

In [42]: 2 < False
Out[42]: False

In [43]: 4 == True
Out[43]: False

In [44]: (4 == True) == 0
Out[44]: True

Upvotes: 2

Related Questions