不能将贝塞尔函数的结果放入numpy的数组中

时间:2014-06-19 17:41:48

标签: python numpy scipy

关注这篇文章:

How to put complex into a numpy's array?

对我来说似乎很有效。

但为什么我在这种情况下会出现这个错误?

  1 #!/usr/bin/env python
  2 import scipy.special
  3 import numpy as np
  4 
  5 deg = 10
  6 nodes = np.polynomial.legendre.leggauss(deg)[0]
  7 A = np.zeros((deg, deg), dtype=complex)
  8 for i in range(0, deg):
  9     for j in range(0, deg):
 10         A[i, j] = scipy.special.sph_yn(0, nodes[i]*nodes[j])[0]


machine:Desktop users$ ./aa.py 
Traceback (most recent call last):
  File "./aa.py", line 10, in <module>
    A[i, j] = scipy.special.sph_yn(0, nodes[i]*nodes[j])[0]
TypeError: can't convert complex to float

补充:如果我在第10行注释并在nest for loop中打印scipy.special.sph_yn(0, nodes[i]*nodes[j])[0],我从sph_yn得到了什么

[-0.61456112]
[-0.79004531]
[-1.19235662]
[-2.16125343]
[-6.82467416]
[ 6.82467416+0.j]
[ 2.16125343+0.j]
[ 1.19235662+0.j]
[ 0.79004531+0.j]
[ 0.61456112+0.j]
... and so on

1 个答案:

答案 0 :(得分:2)

special.sph_yn(0, nodes[i]*nodes[j])[0]返回包含1个元素的numpy数组。您希望将此数组中的值分配给A,而不是数组本身。要从数组中获取单个值,请使用item()方法:

A[i, j] = special.sph_yn(0, nodes[i]*nodes[j])[0].item()

请注意使用列表解析:

A = np.array([[special.sph_yn(0, nodes[i]*nodes[j])[0].item()
               for j in range(deg)]
              for i in range(deg) ])

也可以工作,并且(如果你有内存)比一次为一个NumPy数组赋值一个元素要快。