Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put complex into a numpy's array?

Tags:

python

numpy

>>> import numpy as np
>>> A = np.zeros((3,3))
>>> A[0,0] = 9
>>> A
array([[ 9.,  0.,  0.],
       [ 0.,  0.,  0.],
       [ 0.,  0.,  0.]])
>>> A[0,1] = 1+2j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
>>> A[0,1] = np.complex(1, 2)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float

According to my example code. i tried to put complex number into the numpy's array but it didn't work. May be i miss some basic thing.

like image 282
fronthem Avatar asked Jun 19 '14 09:06

fronthem


People also ask

How do you add an element to an array of an element?

By using ArrayList as intermediate storage: Create an ArrayList with the original array, using asList() method. Simply add the required element in the list using add() method. Convert the list to an array using toArray() method.

Can Numpy handle complex numbers?

NumPy provides the vdot() method that returns the dot product of vectors a and b. This function handles complex numbers differently than dot(a, b). Example 1: Python3.

How do you define a complex array?

A complex array is a data storage term that refers to an array of disks that support data structures in more complex ways than a simple RAID array. Rather than just allowing for multi-disk storage, a complex array can really micro-manage the use of multiple disks to create optimal data transfer and storage solutions.


2 Answers

If you want to create an array containing complex values, you need to specify a complex type to numpy:

>>> A = np.zeros((3,3), dtype=complex)

>>> print A
[[ 0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j]]

>>> A[0,0] = 1. + 2.j

>>> print A
[[ 1.+2.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j]
 [ 0.+0.j  0.+0.j  0.+0.j]]
like image 167
talonmies Avatar answered Sep 28 '22 01:09

talonmies


You need to convert the array's type.

Example:

>>> from numpy import array, dtype
>>> A = array([1, 2, 3])
>>> A[0] = 1+2j
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't convert complex to long
>>> B = A.astype(dtype("complex128"))
>>> B[0] = 1+2j
>>> B
array([ 1.+2.j,  2.+0.j,  3.+0.j])
>>> 
like image 38
James Mills Avatar answered Sep 28 '22 02:09

James Mills