Programming Search⌘K

Conceptcore

Complex numbers in languages

Also called complex type, complex number type, complex data type, complex128, complex64, double complex, _Complex, std::complex, System.Numerics.Complex, num-complex, imaginary literal, cmath.

A complex number type holds a real part and an imaginary part, usually two floats. Some languages have it built in, some in the library and some not at all.

Applies to
core-languages

Idea

A complex number has two parts: a real part a and an imaginary part b, written a + bi, where i times i is -1. Programs for signal processing, electrical circuits, physics and fractal images compute with complex numbers. A complex number type holds the two parts in one value and defines +, -, * and / on them, so the code looks like the mathematics.

"A complex variable or value is usually represented as a pair of floating-point numbers"1. Python has the type as a built-in, with a literal that ends in j:

import cmath

z = 3 + 4j
w = complex(1, -2)
print(z.real, z.imag, abs(z))
print(z + w, z * w, z / w)
print(z.conjugate(), 1j * 1j)
print(cmath.sqrt(-1), cmath.phase(-1))
Output
3.0 4.0 5.0
(4+2j) (11-2j) (-1+2j)
(3-4j) (-1+0j)
1j 3.141592653589793

z.real and z.imag are the two parts, and abs(z) is the distance from 0, which is 5 for 3 + 4j. The product and the quotient follow the rules of complex arithmetic. 1j * 1j is -1, and the square root of -1 is 1j. The module cmath holds the functions for complex numbers.

How it works

Two floats. Most complex types are a pair of floating-point numbers in Cartesian form. In Python, "Complex numbers have a real and imaginary part, which are each a floating-point number"2. Go has two built-in types: complex64, "the set of all complex numbers with float32 real and imaginary parts", and complex128, "the set of all complex numbers with float64 real and imaginary parts"3. A complex128 value uses 16 bytes.

Arithmetic. Languages with a complex type "extend the basic arithmetic operations ('+', '−', '×', '÷') to act on them"1. The rules are:

  • (a + bi) + (c + di) is (a + c) + (b + d)i.
  • (a + bi) * (c + di) is (ac - bd) + (ad + bc)i, because i times i is -1.
  • (a + bi) / (c + di) multiplies the top and the bottom by the conjugate c - di, so the bottom becomes the real number c * c + d * d.

A multiplication takes 4 float multiplications and 2 additions. A division takes more, and a good library also scales the numbers to prevent overflow, as the pitfalls show.

Literals and construction. In Python, "Appending 'j' or 'J' to a numeric literal yields an imaginary number"2, so 3 + 4j is a complex number. In Go, "An imaginary literal represents the imaginary part of a complex constant"3, with the letter i, as in 3 + 4i. C has the macro I in <complex.h>, so 3.0 + 4.0 * I is a double complex. C++ has the literals 1.0i in std::complex_literals, which came in C++144. C# has no literal: new Complex(3, 4) builds the value.

Polar form. A complex number is also a length and an angle: the absolute value (or magnitude) and the phase (or argument). Each library has both: abs and cmath.phase in Python, std::abs and std::arg in C++, cabs and carg in C, cmplx.Abs and cmplx.Phase in Go, and Magnitude and Phase in C#. The functions cmath.polar and cmath.rect, and std::polar in C++, convert between the two forms.

Functions in a separate module. The real math functions do not accept complex numbers, so each language has a second set. Python's cmath "provides access to mathematical functions for complex numbers"5. Go's math/cmplx "provides basic constants and mathematical functions for complex numbers"6. C has csqrt, cexp and the other functions with the prefix c, and C++ overloads std::sqrt and std::exp for std::complex.

Memory layout. The two parts are next to each other in memory, real part first. In C++, "For any object z of type std::complex, reinterpret_cast<T(&)[2]>(z)[0] is the real part of z and reinterpret_cast<T(&)[2]>(z)[1] is the imaginary part of z"4. In Rust, the Complex<T> type of the crate num-complex "is memory layout compatible with an array [T; 2]"7. So an array of complex numbers can go to a C or Fortran library, such as a fast Fourier transform, with no copy.

In languages

LanguageVerdictNote
PythonNative
C++Standard library
JavaAbsentThe Java standard library has no complex type. A program defines a record with two double fields, or uses a library such as Apache Commons Numbers. No example file exists.
CNative
C#Standard library
JavaScriptAbsentJavaScript has no complex type. A program uses an object or an array with two numbers and its own functions, or a library. No example file exists.
TypeScriptAbsentTypeScript has no complex type, as JavaScript. A pair type such as [number, number] with its own functions is the usual form. No example file exists.
GoNative
RustLibraryThe Rust standard library has no complex type. The crate num-complex has Complex<T> with the operators and the functions, and its layout is the same as [T; 2]. No example file exists because the examples use no crates.
KotlinAbsentThe Kotlin standard library has no complex type. A data class with two Double values and operator functions gives the operators. No example file exists because kotlinc is not installed.
SQLAbsentStandard SQL has no complex type. A table stores the real part and the imaginary part in two columns. No example file exists.
BashAbsentBash arithmetic has only integers, so it has no complex numbers. A script uses awk or bc. No example file exists.
PowerShellStandard libraryPowerShell uses the .NET struct [System.Numerics.Complex], with the same operators and properties as C#. No example file exists because pwsh is not installed.
HTMLDoes not applyHTML is markup and has no numbers to compute with.
CSSDoes not applyCSS computes with lengths and other real numbers in calc(), but it has no complex numbers.
Regular expressionsDoes not applyA regular expression matches text and has no numbers.
Language Verdict Mechanism
Python native complex, literals with j, the module cmath
JavaScript absent no complex type; an object with two numbers, or a library
TypeScript absent no complex type, as in JavaScript
Java absent no complex type in the standard library; a record of two double values, or a library
Kotlin absent no complex type in the standard library
C# stdlib System.Numerics.Complex, with double parts
Go native complex64 and complex128, imaginary literals with i, real, imag, the package math/cmplx
Rust library Complex<T> in the crate num-complex
C native double complex and the macro I in <complex.h>; optional, an implementation can define __STDC_NO_COMPLEX__8
C++ stdlib the class template std::complex<T> in <complex>; literals 1.0i
Bash absent no floating-point arithmetic
PowerShell stdlib [System.Numerics.Complex] from .NET
SQL absent no complex type in standard SQL
Regex n/a no numbers
HTML n/a no numbers
CSS n/a no complex numbers

Python, Go and C have the type in the language, with a literal or a macro for i. C++ and C# have it in the standard library as a class or a struct. Java, JavaScript and Rust have no complex type in the standard library, so a program uses a library or writes a small type.

The example files show the type in each language. Python shows the parts, the polar form, parsing from a string and cmath. C shows double complex, CMPLX, cabs and csqrt. C++ shows std::complex, the literal 2.0i, and std::norm, which is the square of the absolute value. C# shows System.Numerics.Complex and its output format. Go shows complex128, the functions real and imag, and math/cmplx.

PythonGitHub
import cmath

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

# The polar form: the length and the angle in radians.
r, phi = cmath.polar(1j)
print(r, phi)
print(cmath.rect(2, 0))

# complex() parses a string with no spaces.
print(complex("1+2j"), complex("-3.5j"))

# cmath accepts negative numbers; math does not.
print(cmath.sqrt(-4), cmath.exp(0j))
print(cmath.isclose(cmath.exp(1j * cmath.pi), -1))
Output
(3+4j) 3.0 4.0 5.0
1.0 1.5707963267948966
(2+0j)
(1+2j) -3.5j
2j (1+0j)
True
  • Verdict: native. complex is a built-in type, and a number with the suffix j is an imaginary literal. abs gives the length, cmath.polar and cmath.rect convert to and from the polar form, and complex() parses a string such as "1+2j". cmath.exp(1j * cmath.pi) is close to -1 but not equal to it, so the comparison uses cmath.isclose.
#include <complex>
#include <iostream>

int main() {
    using namespace std::complex_literals;
    std::complex<double> z{3.0, 4.0};
    auto w = 1.0 - 2.0i;
    std::cout << z * w << ' ' << z / w << '\n';
    std::cout << std::abs(z) << ' ' << std::norm(z) << ' ' << std::arg(1.0i) << '\n';
    std::cout << std::sqrt(std::complex<double>{-4.0, 0.0}) << '\n';
    std::cout << z.real() << ' ' << z.imag() << ' ' << std::conj(z) << '\n';
}
Output
(11,-2) (-1,2)
5 25 1.5708
(0,2)
3 4 (3,-4)
  • Verdict: stdlib. The class template std::complex<T> in <complex> has the operators, and the functions std::abs, std::arg, std::norm, std::conj and std::sqrt accept it. The literal 2.0i comes from std::complex_literals. A stream prints a complex number as (re,im). std::norm is the square of the absolute value, 25 for 3 + 4i, not the length 5.
#include <complex.h>
#include <stdio.h>

int main(void) {
    double complex z = CMPLX(3.0, 4.0);
    double complex w = 1.0 - 2.0 * I;
    double complex p = z * w;
    printf("%g %g\n", creal(p), cimag(p));
    printf("%g %g\n", cabs(z), carg(I));

    // csqrt accepts a negative number.
    double complex s = csqrt(-4.0);
    printf("%g %g\n", creal(s), cimag(s));
    printf("%zu\n", sizeof z);
    return 0;
}
Output
11 -2
5 1.5708
0 2
16
  • Verdict: native. double complex is a type of the language since C99, and <complex.h> gives the macro I, the macro CMPLX and the functions with the prefix c, such as cabs, carg and csqrt. printf has no conversion for complex numbers, so the program prints creal and cimag. A double complex takes 16 bytes. C11 made the support optional, so a compiler can define __STDC_NO_COMPLEX__.
using System;
using System.Numerics;

var z = new Complex(3, 4);
var w = new Complex(1, -2);
Console.WriteLine(z * w);
Console.WriteLine($"{z.Real} {z.Imaginary} {z.Magnitude} {Complex.ImaginaryOne.Phase}");
Console.WriteLine(Complex.Sqrt(-4));
Console.WriteLine(Complex.Conjugate(z) == new Complex(3, -4));
Complex fromInt = 5;
Console.WriteLine(fromInt);
Output
<11; -2>
3 4 5 1.5707963267948966
<0; 2>
True
<5; 0>
  • Verdict: stdlib. System.Numerics.Complex is a struct with two double parts and the operators +, -, *, / and ==. Magnitude and Phase give the polar form, and Complex.Sqrt accepts a negative number. An int or a double converts to Complex with no cast. ToString prints the form <re; im>.
package main

import (
	"fmt"
	"math/cmplx"
	"unsafe"
)

func main() {
	z := complex(3, 4)
	w := 1 - 2i
	fmt.Println(z*w, z/w)
	fmt.Println(real(z), imag(z), cmplx.Abs(z), cmplx.Phase(1i))
	fmt.Println(cmplx.Sqrt(-4), cmplx.Conj(z))
	fmt.Println(unsafe.Sizeof(z), unsafe.Sizeof(complex64(z)))
	fmt.Printf("%.1f\n", z)
}
Output
(11-2i) (-1+2i)
3 4 5 1.5707963267948966
(0+2i) (3-4i)
16 8
(3.0+4.0i)
  • Verdict: native. complex64 and complex128 are built-in types, 2i is an imaginary literal, and the built-in functions complex, real and imag build a value and take it apart. The package math/cmplx has Abs, Phase, Sqrt and the other functions. A complex128 takes 16 bytes and a complex64 takes 8. fmt prints the form (re+imi), and a verb such as %.1f applies to both parts.
  • Polar storage. A type can store the length and the angle in place of the two parts. Multiplication is then cheap, but addition is not, so the common types use the Cartesian form and convert when needed.
  • Integer complex numbers. Complex numbers with integer parts (Gaussian integers) are rare in libraries. In C++, the behavior of std::complex<T> "is unspecified (and may fail to compile)" if T is not a floating-point type4. Go has no integer complex type. The Rust type Complex<T> accepts integer types such as Complex<i32>.
  • Imaginary types. C99 also defines the optional type double imaginary for numbers with no real part, but few compilers have it.
  • Quaternions. Quaternions extend complex numbers to four parts for 3D rotation. They are in graphics libraries, not in the standard libraries of the tier 1 languages.

Pitfalls

  • The real square root does not accept a negative number. math.sqrt(-1) in Python raises ValueError, and sqrt(-1.0) in C returns NaN. Use the complex function, cmath.sqrt or csqrt:

This code runs but gives a wrong answer on purpose.

import cmath
import math

try:
    math.sqrt(-1)
except ValueError as e:
    print(type(e).__name__)
print(cmath.sqrt(-1))
Output
ValueError
1j
  • Complex numbers have no order. < and > have no meaning for complex numbers, so Python raises TypeError, and Go and C++ do not compile the comparison. Compare the absolute values, or the real parts, when an order is necessary:

This code runs but gives a wrong answer on purpose.

try:
    print(1j < 2j)
except TypeError as e:
    print(type(e).__name__)
print(sorted([3 + 4j, 1 - 1j, 2j], key=abs))
Output
TypeError
[(1-1j), 2j, (3+4j)]
  • The simple division formula overflows. The formula with c * c + d * d overflows for large parts, although the quotient is small. A library scales the numbers first:

This code runs but gives a wrong answer on purpose.

def naive_divide(z, w):
    a, b, c, d = z.real, z.imag, w.real, w.imag
    den = c * c + d * d
    return complex((a * c + b * d) / den, (b * c - a * d) / den)


z = complex(1e300, 1e300)
print(naive_divide(z, z))
print(z / z)
Output
(nan+nanj)
(1+0j)
  • Exact comparison of results. The parts are floats, so a result is often not exact. cmath.exp(1j * cmath.pi) is not exactly -1. Compare with a tolerance, such as cmath.isclose.
  • std::norm is not the length. In C++, std::norm(z) is the square of the absolute value, so std::norm of 3 + 4i is 25, not 5. Use std::abs for the length.
  • j alone is a name. In Python, j is a variable name, and 1j is the imaginary unit. 2 * j uses a variable j. In Go, i alone is also a name, and 1i is the imaginary unit.
  • The output format differs. Python prints (3+4j), Go prints (3+4i), C++ prints (3,4) and C# prints <3; 4>. Do not parse one format with the parser of another language.

Cost

A complex value takes the space of two floats: 16 bytes for two 64-bit floats. Addition is two float additions. Multiplication is four float multiplications and two additions, and division needs a division and, in a careful library, a scaling step. The complex functions such as sqrt and exp call several real functions each.

History

Fortran has a COMPLEX type, and the Wikipedia list of languages with a complex type starts with it1. C added complex types in C99: "The C programming language, as of C99, supports complex number math with the three built-in types double _Complex, float _Complex, and long double _Complex"8. C11 made the support optional: if the macro __STDC_NO_COMPLEX__ is defined, "the complex types, the header <complex.h> and all of the names listed here are not provided"8. C++ has the class template std::complex in its standard library, and Go made complex64 and complex128 built-in types3. .NET added the struct Complex in System.Numerics, and its "Complex type uses the Cartesian coordinate system (real, imaginary) when instantiating and manipulating complex numbers"9.

References

  1. Complex data type, Wikipedia, Introduction; Complex-number arithmetic; Language support
  2. Built-in Types, Python documentation, Numeric Types - int, float, complex
  3. The Go Programming Language Specification, Numeric types; Imaginary literals
  4. std::complex, C++ reference, cppreference.com, Template parameters; Array-oriented access; Non-member functions
  5. cmath, Mathematical functions for complex numbers, Python documentation, Introduction
  6. Go standard library, math/cmplx, Overview
  7. Complex in num_complex, docs.rs, Representation and Foreign Function Interface Compatibility
  8. Complex number arithmetic, C reference, cppreference.com, Introduction
  9. Complex Struct, .NET API reference, Remarks

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/AFWVZY/text.yaml