Strange results

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Strange results

Andrzej Kapanowski
Hello!

My friend noticed strange results from Python 2.5.2:

>>> b=47
>>> 0-b/2
-23
>>> -b/2+0
-24

Anybody can explain that?

Regards,
Andrzej Kapanowski


_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: Strange results

kirby urner-4
On Tue, Jan 3, 2012 at 2:23 AM, Andrzej Kapanowski <[hidden email]> wrote:

> Hello!
>
> My friend noticed strange results from Python 2.5.2:
>
>>>> b=47
>>>> 0-b/2
> -23
>>>> -b/2+0
> -24
>
> Anybody can explain that?
>

It's integer division:

>>> -1/2
-1
>>> 1/2
0

Not symmetrical.  Why?

http://www.peterbe.com/Integer-division-in-programming-languages

Helps some maybe.

Kirby

> Regards,
> Andrzej Kapanowski
>
>
> _______________________________________________
> Edu-sig mailing list
> [hidden email]
> http://mail.python.org/mailman/listinfo/edu-sig
>
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: Strange results

Christian Mascher
In reply to this post by Andrzej Kapanowski
Hi,

apart from integer-division (see Kirby's post) the result also depends
on different interpretations of the operator "-":

> My friend noticed strange results from Python 2.5.2:
>
>  >>> b=47
>  >>> 0-b/2
> -23

is interpreted as 0 - ( b/2) so integer division comes first before
subtraction (- as subtraction operator).

>  >>> -b/2+0
> -24
>

is interpreted like ( (-1) * b ) / 2 + 0
so a leading - is applied like a _multiplication_ and because * and /
are on equal levels of execution, the left-most is evaluated first.

Always interesting how seemingly simple and "straightforward" rules can
trip you in special circumstances. Parentheses are recommended if you
want to be sure.

Happy new year

Christian

> Anybody can explain that?
>
> Regards,
> Andrzej Kapanowski
>
>
> ------------------------------------------------------------------------
>
> _______________________________________________
> Edu-sig mailing list
> [hidden email]
> http://mail.python.org/mailman/listinfo/edu-sig

_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig