1

How do I make an array of complex numbers in Python?

In C++ STL we can write the following code:

class Complex {

      public:
      int re, 
          im;

      float getModule() {

            return sqrt(re * re + im * im);
      } 
};

vector< Complex > vec;

but in Python?

3
  • You can put anything you like in a list: [1+2j]. Or do you mean an array.array? Commented Sep 24, 2015 at 15:11
  • Lika any other array. Complex numbers in Python Commented Sep 24, 2015 at 15:12
  • by the way, C++ does have a proper complex type, don't use your own. Commented Sep 24, 2015 at 15:36

6 Answers 6

3

Python has built-in support for complex numbers. You can just enter them like that:

>>> a = 2 + 3j # or: complex(2,3)
>>> a
(2+3j)
>>> type(a)
<type 'complex'>
>>> a.real
2.0
>>> a.imag
3.0
>>> 

As for the container, in Python you can start with a list:

>>> complex_nums_list = [2+3j, 3+4j, 4+5j]
>>> complex_nums_list
[(2+3j), (3+4j), (4+5j)]

Or you can use numpy.array, which would be more suited for numerical applications.

Sign up to request clarification or add additional context in comments.

Comments

2

Extremely simple:

Python's has both a native list and a native complex type, so:

c = complex(real,imag)

or just

c = 1 + 2j

does the trick of creating one;

complexes = [ complex(i, i) for i in range(100) ] 

creates thousand complex values in a list complexes.

You might want to have a look at numpy:

import numpy
arr = numpy.ndarray(1000, dtype=numpy.complex128)

Comments

0

You just create the list of values:

vec = [1+2j, 3+4j]

Comments

0

You can use the built-in complex class.

Or just use a complex literal: Python uses j for the imaginary unit.

z = complex(3, 4)
print(z, z.real, z.imag)

z = 3 + 4j
print(z)

output

(3+4j) 3.0 4.0
(3+4j)

The complex constructor also takes keyword arguments, so you can do

z = complex(real=3, imag=4)

with the args in either order. And that also means that you can even pass the args in a dict, if you want:

d = {'real': 3, 'imag': 4}
z = complex(**d)

There's also a built-in cmath module for mathematical functions of complex arguments.

Comments

0

A pure Python approach:

array_size = 10
vec = [complex()] * array_size

This will create a list of 10 empty complex numbers.

You can then set the first and second elements, if you want,

vec[0] = complex(2. , 2.,)   # complex number 2+2j
vec[1] = 2 + 2j

or append a new element to your list:

vec.append(3 + 3j)

Comments

-3

Actually, I want to sort numbers complex according to their module. This is my turn.

import math

class Complex:
  def __init__( self, a, b ): 
      self.a = a
      self.b = b

  def getModule( self ):
      return math.sqrt( self.a**2 + self.b**2 )

  def __str__( self ):
  ''' Returns complex number as a string '''
      return '(%s + i %s)' % (self.a, self.b)

  def add(self, x, y):
      return Complex(self.a + x, self.b + y) 

  def sub(self, x, y):
      return Complex(self.a - x, self.b - y) 


  #input = [[2, 7],[5, 4],[9, 2],[9, 3],[7, 8], [2, 2], [1, 1]]

  # Read the input from a given file complex.in, 
  # in fact is a matrix with Nx2 dimensions
  # first  line re1 im1 
  # second line re2 im2
  # ...
  #Example complex.in
  #5
  #2 7
  #5 4
  #9 2
  #9 3
  #7 8

  f = open('complex.in','r')

  input = [map(int, line.split(' ')) for line in f]

  del input[0]

  num = len( input )

  complexes = [ Complex( i[ 0 ], i[ 1 ] ) for i in input ]

  def swapp(c, a, b):

      c[ a ], c[ b ] = c[ b ], c[ a ] 

  def sort( c ):

      swapped = 1

      for i in range(num - 1, 0, -1):

      swapped = 1

      for j in range(0, i):

          if c[ j ].getModule() > c[ j + 1 ].getModule():

             swapped = 0

             swapp(c, j, j + 1)

      if swapped:

         break   

  sort( complexes )

  f = open('complex.out','w')

  for c in complexes:

      f.write('%s\n' % c)     
      print c 

3 Comments

PLEASE. Properly format code. It would have been one click on the "format as code" button. Can't be that hard.
also, what you call module is called "absolute value" for most people. And sorting is easy: list_of_complexes = [1+2j, 2, -10+0.5j]; sorted_list = sorted(list_of_complexes, cmp=abs)
don't implement a complex class in languages that already have one -- you won't be able to use their feature-rich standard libraries for complex math on your own type. This goes for both python and C++.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.