问题
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.
回答1:
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)
回答2:
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".
来源:https://stackoverflow.com/questions/40578746/compatibility-between-sage-and-numpy