Inverting integers in Sage gives different behaviour than in Python

25 views
Skip to first unread message

Mark Bell

unread,
Dec 21, 2015, 11:32:03 AM12/21/15
to sage-support
The __invert__ methods, which controls the behaviour of the ~ operator, of Integers and ints are different.

In Python, for an int x, its invert ~x is defined to be its two's complement and is given by -1-x.

On the other hand, in Sage for an Integer x (from sage.rings.integer.Integer), its __invert__ is defined to be 1 / x.

Unfortunately this difference means that ~x different results in Sage and Python and so is causing some of my scripts and packages that run under Python to break under Sage. Most notably, that under Sage ~0 raises a "ZeroDivisionError: Rational division by zero" error rather than returning -1.

Looking through the git history it appears that this has been the convention since at least October 2006. Is there a reason why __invert__ was chosen to act this way rather than match the Python convention?

Emmanuel Charpentier

unread,
Dec 21, 2015, 1:05:13 PM12/21/15
to sage-support

maybe because :
sage: var("x")
x
sage: ~x
1/x
sage: var("a,b,c,d")
(a, b, c, d)
sage: M=matrix([[a,b],[c,d]])
sage: ~M
[1/a - b*c/(a^2*(b*c/a - d))           b/(a*(b*c/a - d))]
[          c/(a*(b*c/a - d))              -1/(b*c/a - d)]

were deemed useful ?

HTH,
--
Emmanuel Charpentier
Reply all
Reply to author
Forward
0 new messages