a *= b not equivalent to a = a*b
Peter Otten
__peter__ at web.de
Fri Aug 26 02:51:06 EDT 2016
mlz wrote:
> I've been playing with the binomial function, and found that in the below
> code, rs *= x does not behave the same way as rs = rs * x. When I set FAIL
> to True, I get a different result. Both results are below.
>
> I had read that the two were equivalent. What am I missing?
>
> thanks,
> -= miles =-
>
>
> #!/usr/bin/python2
>
> import sys
> FAIL= True if len(sys.argv)>1 else False
>
> def bin(n,k):
> rs=1
> k=min(k,n-k)
>
> for i in range(1,k+1):
> if FAIL: rs *= (n-(i-1))/i # these should be the same,
This is evaluated as
rs = rs * ((n - (i - 1)) / i)
> else: rs = rs * (n-(i-1))/i # but apparently are not
while this is evaluated as
rs = (rs * (n - (i - 1))/i
so the two expressions do not really result in the same calculation. A
simpler example:
>>> (2*2)/3
1
>>> 2*(2/3)
0
Now "hide" the the order of evaluation:
>>> a, b = 2, 3
>>> a *= a/b
>>> a
0
>>> a, b = 2, 3
>>> a = a*a/b
>>> a
1
> return rs
>
>
> for n in range(10):
> for k in range(n+1):
> print bin(n,k),
> print''
>
> ------------------- output -------------------------
>
>
> $ pascal2
> 1
> 1 1
> 1 2 1
> 1 3 3 1
> 1 4 6 4 1
> 1 5 10 10 5 1
> 1 6 15 20 15 6 1
> 1 7 21 35 35 21 7 1
> 1 8 28 56 70 56 28 8 1
> 1 9 36 84 126 126 84 36 9 1
>
> $ pascal2 fail
> 1
> 1 1
> 1 2 1
> 1 3 3 1
> 1 4 4 4 1
> 1 5 10 10 5 1
> 1 6 12 12 12 6 1
> 1 7 21 21 21 21 7 1
> 1 8 24 48 48 48 24 8 1
> 1 9 36 72 72 72 72 36 9 1
More information about the Python-list
mailing list