fronthem
fronthem

Reputation: 4139

Can not put the result of Bessel function into numpy's array

Following to this post:

How to put complex into a numpy's array?

It seems work well for me.

But why did i get this error in this case?

  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

Additional: What did i get from sph_yn if i comment line 10 and print scipy.special.sph_yn(0, nodes[i]*nodes[j])[0] out in nest for loop

[-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

Upvotes: 1

Views: 202

Answers (1)

unutbu
unutbu

Reputation: 880339

special.sph_yn(0, nodes[i]*nodes[j])[0] returns a numpy array containing 1 element. You want to assign the value inside this array to A, not the array itself. To get the single value out of the array, use the item() method:

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

Note that using a list comprehension:

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

would also work, and (if you have the memory) is faster than assigning values to a NumPy array one element at a time.

Upvotes: 2

Related Questions