Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning complex values to numpy arrays?

Tags:

This gives the expected result

x = random.rand(1) + random.rand(1)*1j print x.dtype print x, x.real, x.imag 

and this works

C = zeros((2,2),dtype=complex) C[0,0] = 1+1j print C 

but if we change it to

C[0,0] = 1+1j + x 

I get "TypeError: can't convert complex to float".

If we now omit the explicit dtype = complex, I get "ValueError: setting an array element with a sequence".

Can someone explain what's going on, and how to do this without errors? I'm lost.

like image 471
gibson Avatar asked Feb 25 '14 14:02

gibson


People also ask

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.

Do NumPy supports complex data type?

NumPy supports a much greater variety of numerical types than Python does. This section shows which are available, and how to modify an array's data-type. Platform-defined double precision float: typically sign bit, 11 bits exponent, 52 bits mantissa.

How do I assign an element to a NumPy array?

Element Assignment in NumPy Arrays We can assign new values to an element of a NumPy array using the = operator, just like regular python lists.


1 Answers

Actually, none of the proposed solutions worked in my case (Python 2.7.6, NumPy 1.8.2). But I've found out, that change of dtype from complex (standard Python library) to numpy.complex_ may help:

>>> import numpy as np >>> x = 1 + 2 * 1j >>> C = np.zeros((2,2),dtype=np.complex_) >>> C array([[ 0.+0.j,  0.+0.j],        [ 0.+0.j,  0.+0.j]]) >>> C[0,0] = 1+1j + x >>> C array([[ 2.+3.j,  0.+0.j],        [ 0.+0.j,  0.+0.j]]) 
like image 131
Lenka42 Avatar answered Oct 17 '22 01:10

Lenka42