在SAGE中跨越两个numpy(向量定义的函数)数组时出错

时间:2014-12-28 16:56:24

标签: python arrays numpy sage

u=u(x),v=v(x)成为SAGE中定义的两个向量函数,如下所示:

import numpy as np
x = var('x')
f,g = function('f',x), function('g',x)
f(x), g(x) = 2*x, sin(x)
u,v = np.array([f,g]),np.array([g,f])
c = np.cross(u,v)

尝试越过u,v时出现以下错误(看起来很奇怪,因为np.dot(u,v)效果很好)

错误:

sage: np.cross(u,v,axisa=0,axisb=0)
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-12-4f0f99d7c55e> in <module>()
----> 1 np.cross(u,v,axisa=Integer(0),axisb=Integer(0))

/usr/lib/sagemath/local/lib/python2.7/site-packages/numpy/core/numeric.py in cross(a, b, axisa, axisb, axisc, axis)
   1329         if (b.shape[0] == 2):
   1330             cp = a[0]*b[1] - a[1]*b[0]
-> 1331             if cp.ndim == 0:
   1332                 return cp
   1333             else:

/usr/lib/sagemath/local/lib/python2.7/site-packages/sage/structure/element.so in sage.structure.element.Element.__getattr__ (sage/structure/element.c:3846)()

AttributeError: 'sage.symbolic.expression.Expression' object has no attribute 'ndim'

更新(解决方案):在3D矢量上使用SAGE&#39; u.cross_product(v)

1 个答案:

答案 0 :(得分:0)

由于ab的第一个昏暗是2,它正在计算

cp = a[0]*b[1] - a[1]*b[0]

对于普通的numpy数组,这很好用:

np.cross([1,2],[2,1])  # -3

,因为

np.array([1,2])[0].ndim  # 0

我没有Sage,但是您的错误消息表明数组的元素是sage.symbolic.expression.Expression个对象。

我可以使用dtype=object的其他数组重现您的错误:

In [79]: f=np.array((1,2),dtype='O')  # array([1, 2], dtype=object)
In [80]: g=np.array((2,1),dtype='O')

In [83]: np.cross(f,g)
...
-> 1501             if cp.ndim == 0:
   1502                 return cp
   1503             else:

AttributeError: 'int' object has no attribute 'ndim'

In [84]: np.dot(f,g)
Out[84]: 4

In [86]: f[0]
Out[86]: 1

In [87]: f[0].ndim
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-87-45759919b9dd> in <module>()
----> 1 f[0].ndim

AttributeError: 'int' object has no attribute 'ndim'

显然,当np.cross被写入时,他们不希望它与对象数组一起使用。通过此测试会产生错误的那些:if cp.ndim == 0: