Examples of how to get the modulus of complex number in python:
Definition
The modulus of complex number $z=a+ib$ is:
\begin{equation}
|z| = |a+ib| = \sqrt{a^2+b^2}
\end{equation}
with $a$ and $b$ are the real and imaginary parts.
Create a function to calculate the modulus of complex number
To calculate the modulus of complex number a solution is to define a simple python function:
>>> import math>>> def complexe_modulo(z):... a = z.real... b = z.imag... return math.sqrt(a**2+b**2)...
So for example with the complex number
>>> z = 1 + 1.j
the function defined above returns:
>>> complexe_modulo(z)1.4142135623730951
Using the built-in function abs()
Another solution is to use the function abs(). For example with the complex number
>>> z = 1 + 1.j>>> z(1+1j)
the function abs() returns:
>>> abs(z)1.4142135623730951
Matrix of complex numbers
Example with a complex number matrix:
>>> import numpy as np>>> Z = np.array([[1+2j,1+3j],[5+6j,3+8j]])>>> Zarray([[ 1.+2.j, 1.+3.j],[ 5.+6.j, 3.+8.j]])>>> np.abs(Z)array([[ 2.23606798, 3.16227766],[ 7.81024968, 8.54400375]])
References
| Links | Site |
|---|---|
| Complex modulus | wikipedia |
| numpy.absolute | doc scipy |
| Most memory-efficient way to compute abs()**2 of complex numpy ndarray | stackoverflow |
