Y. Pei
Y. Pei

Reputation: 345

compatibility between sage and numpy

Here are two lines of code for the purpose of generating a random permutation of size 4:

from numpy import random
t = random.permutation(4)

This can be executed in Python, but not sage, which gives the following error:

TypeError                                 Traceback (most recent call last)
<ipython-input-3-033ef4665637> in <module>()
      1 from numpy import random
----> 2 t = random.permutation(Integer(4))

mtrand.pyx in mtrand.RandomState.permutation (numpy/random/mtrand/mtrand.c:34842)()

mtrand.pyx in mtrand.RandomState.shuffle (numpy/random/mtrand/mtrand.c:33796)()

TypeError: len() of unsized object

Why?

A bit more details: I executed the code in Python 3, and the mtrand is also in the Python 3 directory, which should rule out the possibility that sage is calling Python 2 version of the numpy.

Upvotes: 3

Views: 1070

Answers (2)

Samuel Leli&#232;vre
Samuel Leli&#232;vre

Reputation: 3453

To escape Sage's preparser, you can also append the letter r (for "raw") to numerical input.

from numpy import random
t = random.permutation(4r)

The advantage of 4r over int(4) is that 4r bypasses the preparser, while int(4) is preparsed as int(Integer(4)) so that the Python integer is transformed into a Sage integer and then transformed back into a Python integer.

In the same way, 1.5r will give you a pure Python float rather than a Sage "real number".

Upvotes: 3

John Palmieri
John Palmieri

Reputation: 1696

The reason this doesn't work in Sage is that Sage preparses its input, turning "4" from a Python int to a Sage Integer. In Sage, this will work:

from numpy import random
t = random.permutation(int(4))

Or you can turn the preparser off:

preparser(False)
t = random.permutation(4)

Upvotes: 2

Related Questions