# Why is SageMath generating errors during compilation?

Whenever compile the following codes, it generates errors. But I don't know why is such errors occurred.

 F.<x> = GF(3^15)
def NP(a):
return F(a.digits(3))

import random
b=[0,0]
for r in srange(0,2):
b[r]=random.randint(0,3^15-1)

for i in srange(1,4):
q=NP(b)+NP(b)
print q


Here are the errors:

 File "file.sage.py", line 16, in <module>
q=NP(b[_sage_const_0 ])+NP(b[_sage_const_1 ])
File "file.sage.py", line 8, in NP
return F(a.digits(_sage_const_3 )) #integer 2 polynomial
AttributeError: 'int' object has no attribute 'digits'

edit retag close merge delete

Sort by » oldest newest most voted

This is because random.randint(0,3^15-1) returns a Python int and not a Sage Integer, and only this latter has a digits method. To fix this, you can either

• convert this int into a Sage Integer, by replacing random.randint(0,3^15-1) with ZZ(random.randint(0,3^15-1))

or

• ask Sage to directly produce a random Sage integer, by replacing random.randint(0,3^15-1) with ZZ.random_element(0,3^15) Note that in this case, the upper bound becomes excluded by default, so you have to remove the -1.
more The issue is that Python integers are not the same as Sage integers: Sage integers have more functionality. The command random.randint(...) returns a Python integer, so you need to convert it to a Sage integer, for example with

b[r]=Integer(random.randint(0,3^15-1))


I would also recommend changing the last line to

print(q)


The syntax print q will stop working with recent releases of Sage. (print with no parentheses is valid Python 2 syntax but not valid Python 3 syntax, and as of version 9.0, Sage is based on Python 3.)

more