Function randint() does not return an integer

725 views Asked by At

I faced a curious problem while taking the writing of an integer in bits in Python (I am working in Sage)

I first tried to run the code

m=7
m.bits()

Everything worked fine there. Then, I wanted to do this with a random integer. Thus, I tried to run the code

import random
m=randint(2,10)
m.bits()

That is where I got the error "AttributeError: 'int' object has no attribute 'bits'" as if the function randint was not returning an integer. I managed to force it to be an integer by doing

m=m+0

However, I am still wondering why the first writing was not working. I have to say that I am coding on online sage, even if I do not think this should be an issue.

Thanks in advance!

1

There are 1 answers

0
kcrisman On BEST ANSWER

For a random Sage integer (using various distributions), use ZZ.random_element (doc here). Try this example:

a = ZZ.random_element(2,10)
a.bits()

I've opened Trac 22131 to clarify this issue; one shouldn't have to do something quite this elaborate, there could be a random_integer function at the top level. (There is a random_prime, for instance.)