use of is instead of ==

9 views
Skip to first unread message

smichr

unread,
Aug 4, 2011, 5:23:36 AM8/4/11
to mpmath
In ctx_mp_python.py the expression `other is 0` is being used. Will
this always work or should `other == 0` be used?

Fredrik Johansson

unread,
Aug 4, 2011, 5:39:27 AM8/4/11
to mpm...@googlegroups.com
On Thu, Aug 4, 2011 at 11:23 AM, smichr <smi...@gmail.com> wrote:
> In ctx_mp_python.py the expression `other is 0` is being used. Will
> this always work or should `other == 0` be used?

It should always work. The result is the same regardless of the branch
chosen, but it runs a bit faster on CPython because "is 0" avoids an
expensive comparison with an mpmath number.

Fredrik

Aaron Meurer

unread,
Aug 4, 2011, 5:39:08 AM8/4/11
to mpm...@googlegroups.com
No, that won't work in pypy, so it should be changed. See issue 1026.

Aaron Meurer

On Thu, Aug 4, 2011 at 3:23 AM, smichr <smi...@gmail.com> wrote:
> In ctx_mp_python.py the expression `other is 0` is being used. Will
> this always work or should `other == 0` be used?
>

> --
> You received this message because you are subscribed to the Google Groups "mpmath" group.
> To post to this group, send email to mpm...@googlegroups.com.
> To unsubscribe from this group, send email to mpmath+un...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/mpmath?hl=en.
>
>

Fredrik Johansson

unread,
Aug 4, 2011, 5:43:35 AM8/4/11
to mpm...@googlegroups.com

In fact, 'other == 0' would be wrong because it would cause an mpf to
be returned instead of an mpc when the sum is a complex number with
zero imaginary part.

The code would be correct if the "False" branch were always taken. The
"is 0" check is just an optimization for CPython that speeds up very
short sums of real numbers. I guess it could be commented as such.

Fredrik

Aaron Meurer

unread,
Aug 4, 2011, 6:13:12 AM8/4/11
to mpm...@googlegroups.com
Ah, sorry. I didn't bother reading the code. Usually people write "is
0" when they mean "== 0", and it works in CPython because it
singletonizes small integers, but then it breaks in pypy. But I
suppose it would be possible to write code that actually takes this
fact into consideration as an optimization without breaking when it
doesn't hold.

Indeed a comment would be helpful.

Aaron Meurer

On Thu, Aug 4, 2011 at 3:43 AM, Fredrik Johansson

Reply all
Reply to author
Forward
0 new messages