Here's a summary of things that might be useful when dealing with complex numbers in Python

I usually write a quantum computer simulator in Python. For that reason, I use complex numbers very often.

Python and numpy also support complex numbers, so it's not too much trouble, but there are some traps, so I will summarize them.

The basics of complex numbers in Python

This is the one you normally find in the reference. Lightly review.

The imaginary unit is 1j and the type is complex

Mathematics often uses i for the imaginary unit, while Python uses 1j. (In fields such as electricity, I have seen that the imaginary unit is set to j because i is used for electric current, but I do not know anything else in other fields.)

You can also write something like 2j or 1.23j. (Normally means twice as much as 1j, 1.23 times) Whereas 1 and 1. have different types, 1j and 1.j are both the same.

ʻA + b * 1. jcan also be written ascomplex (a, b)`, where a and b are floats.

Take the real and imaginary parts with .real, .imag and take the complex conjugate with conjugate ()

(1 + 2j) .real is 1, (1 + 2j) .imag is 2. Note that we don't add () as it is not a method. Complex conjugates use .conjugate (), such as (1 + 2j) .conjugate (). Since this is a method, () is required. By the way, .real, .imag, conjugate () can actually be used for float and int.

numpy can also be used normally

Even with numpy, you can use complex numbers normally, such as np.array ([1 + 2j, 3, 4j, 5 + 6.7j]). At this time, dtype defaults to'complex128'. .real, .imag, .conjugate () can also be used for numpy arrays. Also, in numpy, you can use .conj () instead of .conjugate ().

In addition, it is necessary to use .conj (). T to take the Hermitian conjugate of the matrix, which is a little troublesome. With np.matrix, it was possible with .H. It doesn't seem to be in np.array.

cmath instead of math

Use ʻimport cmath instead of ʻimport math. Whereas the function of math takes a domain or range as a real number, cmath also contains a complex number in the domain or range. See Official Documentation for details.

There are also useful functions such as phase () to find the argument of a complex number, polar () to return a tuple of radius and declination, and rect () to create a complex number from radius and declination. ..

Precautions when dealing with complex numbers in Python

I will write some traps and how to deal with them.

If it can be a complex number, make the numpy array in advance with a complex number

Python implicitly converts the type without writing the type yourself, but in numpy, the array has a type, and the type of the array does not change arbitrarily. (The same is true if the int array does not become a float)

a = np.array([1., 2.]) #dtype is float64
a *= 1j
# UFuncTypeError: Cannot cast ufunc 'multiply' output from dtype('complex128') to dtype('float64') with casting rule 'same_kind'

To prevent this from happening Specify the type from the beginning like np.array ([1., 2.], dtype = np.complex128), or It is necessary to include complex numbers from the beginning like np.array ([1 + 0j, 2.], dtype = np.complex128).

The inner product of complex vectors is np.vdot instead of np.dot

This is really a trap.

The inner product of the complex vector is the sum of the product of the complex conjugate of $ u $ and the product of each component of $ v $, such as $ u \ cdot v = \ sum_ {i = 1} ^ n u_i ^ * v_i $. Is normal, but in np.dot, the sum of the products of each component is taken as it is without taking the complex conjugate. If you really need to use np.dot, use the complex conjugate yourself. On the other hand, if you use np.vdot, you can get the inner product properly even if it is a complex vector.

Obviously, complex numbers cannot be compared in size.

Obviously for anyone working with complex numbers in other languages. Complex numbers cannot be compared.

More precisely, it is not possible to compare the magnitude of "complex type", so even if the programmer knows that the calculation result is a real number, if it is a complex number type for the computer, it cannot be compared. It must be a real number, such as .real.

There seems to be no efficient way to "square the absolute value" of a complex array

Since np.abs internally calculates something likesqrt (real ** 2 + imag ** 2), it is wasteful to square it. On the other hand, if you write a calculation like ʻarr.real ** 2 + arr.imag ** 2` on the Python side, it will not be calculated in-place, resulting in wasted memory allocation. I've checked it before, but StackOverflow says that numba can be used -of-complex-numpy-ndarray). It seems that there is no surprising way to do it without unnecessary square root extraction in-place with only Python and numpy.

Recommended Posts

Here's a summary of things that might be useful when dealing with complex numbers in Python
Summary of points to keep in mind when writing a program that runs on Python 2.5
A summary of Python e-books that are useful for free-to-read data analysis
Precautions when dealing with control structures in Python 2.6
Character encoding when dealing with files in Python 3
I made a familiar function that can be used in statistics with Python
The story of Django creating a library that might be a little more useful
Summary of statistical data analysis methods using Python that can be used in business
Precautions when dealing with ROS MultiArray types in Python
Things to note when initializing a list in Python
What's in that variable (when running a Python script)
Create a flag in settings that will be True only when testing with Django
[Python] Introduction to web scraping | Summary of methods that can be used with webdriver
Summary of things that were convenient when using pandas
Japanese output when dealing with python in visual studio
Can be used with AtCoder! A collection of techniques for drawing short code in Python!
A story that went missing when I specified a path starting with a tilde (~) in python open
Format summary of formats that can be serialized with gensim
Summary of things that need to be installed to run tf-pose-estimation
Processing of python3 that seems to be usable in paiza
Let's create a script that registers with Ideone.com in Python.
[For beginners] Summary of standard input in Python (with explanation)
Use a macro that runs when saving python with vscode
Note links that may be useful when using Python, Selenium2
Things to keep in mind when using Python with AtCoder
Scripts that can be used when using bottle in Python
Precautions that must be understood when building a PYTHON environment
Things to keep in mind when using cgi with python.
A set of script files that do wordcloud in Python3
Handle complex numbers in Python
How to write when you want to put a number after the group number to be replaced with a regular expression in re.sub of Python
A story that didn't work when I tried to log in with the Python requests module
About the matter that torch summary can be really used when building a model with Pytorch
[Python] A program that finds the maximum number of toys that can be purchased with your money
The story of creating a bot that displays active members in a specific channel of slack with python
How to not escape Japanese when dealing with json in python
A brief summary of Graphviz in python (explained only for mac)
Be careful of LANG for UnicodeEncodeError when printing Japanese with Python 3
A record that GAMEBOY could not be done in Python. (PYBOY)
Make a Spinbox that can be displayed in Binary with Tkinter
I tried to create a list of prime numbers with python
Here's a brief summary of how to get started with Django
A function that measures the processing time of a method in python
I made a shuffle that can be reset (reverted) with Python
Python standard input summary that can be used in competition pro
Parallel computing (pathos) when dealing with objects that cannot be pickled
Make a Spinbox that can be displayed in HEX with Tkinter
What's new in datetime that is a bit more useful in Python 3
Get a list of files in a folder with python without a path
The story of making a module that skips mail with python
Testing with random numbers in Python
Workaround memo when Segmentation fault: 11 appears in import of opencv that was brew installed with virtualenv of python
[Python] Code that can be written with brain death at the beginning when scraping as a beginner
Law of large numbers in python
Until dealing with python in Atom
When writing a program in Python
Basic summary of scraping with Requests that beginners can absolutely understand [Python]
Get a list of packages installed in your current environment with python
gRPC-Methods used when dealing with protocol buffers types in Python CopyFrom, Extend
I made a Discord bot in Python that translates when it reacts
[Python memo] Be careful when creating a two-dimensional array (list of lists)