Ask Your Question
0

Sage seems to accept a Python nonsense. Why ?

asked 2023-12-24 14:46:40 +0100

Emmanuel Charpentier gravatar image

updated 2023-12-25 08:54:48 +0100

FrédéricC gravatar image

Seen there :

sage: var("r")
r
sage: type(2r^2)
<class 'int'>

I do not understand what meaning the 2r^2 can have for the sage interpreter. The preparser does not try to interpret it,transforms ^ in **, adds a type to the second 2, ignores the first one and deletes the r :

sage: preparse('2r^2')
'2**Integer(2)'

I do not understand why.

Furthermore :

sage: Integer(2r^2)
4

The int interpretation is genuine...

sage: (2r^2).n()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
Cell In[13], line 1
----> 1 (2**Integer(2)).n()

AttributeError: 'int' object has no attribute 'n'

... and consistent. But I still do not understand why this is not rejected.

This seems specific to Sage's symbolic variables ; counter-examples :

sage: import sympy
sage: t=sympy.symbols("t")
sage: 2t^2
  Cell In[23], line 1
    2t**Integer(2)
    ^
SyntaxError: invalid decimal literal

sage: u=function("u")
sage: 2u^2
  Cell In[27], line 1
    2u**Integer(2)
    ^
SyntaxError: invalid decimal literal

This behavior is what I'd expect in the r case.

Any explanation welcome.

BTW, shouldn't we consider this as a bug ?

edit retag flag offensive close merge delete

1 Answer

Sort by » oldest newest most voted
2

answered 2023-12-24 18:05:16 +0100

This is because of the Sage preparser — search for "raw literals" on that page. In particular "2r" is interpreted as a "raw" integer as opposed to a Sage integer.

sage: type(2r) # a Python int, not a Sage Integer
<class 'int'>
edit flag offensive delete link more

Comments

Aaaarghhh ! The r "variable name" "specialcases" in the preparser. I didn't know that.

Thank you very much !

Emmanuel Charpentier gravatar imageEmmanuel Charpentier ( 2023-12-24 20:02:27 +0100 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower

Stats

Asked: 2023-12-24 14:46:40 +0100

Seen: 283 times

Last updated: Dec 24 '23