Sage和NumPy之间的兼容性

3

以下是两行代码,用于生成大小为4的随机置换:

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

这可以在Python中执行,但不可以在Sage中执行,会出现以下错误:
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

为什么?

稍微详细一些:我在Python 3中执行了代码,并且 mtrand 也在Python 3目录中,这应该排除了sage调用numpy的Python 2版本的可能性。


然而,目前Sage仅支持Python 2(尽管这很可能会在不久的将来改变,请参见https://trac.sagemath.org/ticket/15530)。 - kcrisman
2个回答

3
为了避免Sage预处理器的影响,你还可以在数字输入后面加上字母r(表示“原始”)。
from numpy import random
t = random.permutation(4r)
4r 相较于 int(4) 的优势在于,4r 可以绕过预解析器,而 int(4) 则被预解析为 int(Integer(4)),这样 Python 整数就会被转换成 Sage 整数,再被转回 Python 整数。
同样地,1.5r 会给你一个纯 Python 浮点数,而不是 Sage "实数"。

2
这个在Sage中不能工作的原因是Sage预处理其输入,将Python中的“4”转换为Sage中的“Integer”。在Sage中,这将起作用:
from numpy import random
t = random.permutation(int(4))

或者您可以关闭预解析器:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接