compatibility between sage and numpy

冷暖自知 提交于 2019-12-11 01:23:38

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!