Programming Search⌘K

Taskcore

Do complex number arithmetic

Also called complex arithmetic, add complex numbers, multiply complex numbers, divide complex numbers, complex division, complex conjugate, complex absolute value, complex phase, argument of a complex number, cmath, math/cmplx, std::complex, System.Numerics.Complex.

Add, multiply and divide two complex numbers, and find the absolute value and the phase. Use the built-in or library type, or a small type of your own.

Task

Add, multiply and divide two complex numbers, and find the absolute value and the phase of a complex number. The Rosetta Code task says: "Show addition, multiplication, negation, and inversion of complex numbers in separate functions"1. It also says: "Some languages have complex number libraries available"1. If a language has a complex type, use it. If it does not, define a small type.

The function complex_arithmetic(a, b) takes two complex numbers as pairs [re, im]. It returns a list of 8 numbers: the sum a + b, the product a * b and the quotient a / b, each as a real part and an imaginary part, then the absolute value of a and the phase of a. For a = 3 + 4i and b = 1 - 2i, the result is [4, 2, 11, -2, -1, 2, 5, 0.927...].

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. The bottom becomes the real number c * c + d * d.
  • The absolute value of a + bi is the square root of a * a + b * b, the distance from 0.
  • The phase (or argument) is the angle from the positive real axis, atan2(b, a). "One possible choice to uniquely specify the argument (also known as choosing a principal value) is to require it to be within the interval" from -π to π2.

Subtraction and the reciprocal follow from these rules: a - b is a + (-b), and 1 / b is the quotient with a = 1.

Solutions

Language Complex type Division
Python the built-in complex, and cmath.phase the operator /
JavaScript, TypeScript none; functions on pairs [re, im] a scaled formula
Java none; a record with two double fields a scaled formula
C# System.Numerics.Complex the operator /
Go the built-in complex128, and math/cmplx the operator /
Rust none in the standard library; a struct with two f64 fields a scaled formula
C double complex in <complex.h> the operator /
C++ std::complex<double> in <complex> the operator /
Bash none; awk does the floating-point work a scaled formula
  • Python. complex(*a) makes a complex number from a pair. abs(z) is the absolute value, and cmath.phase(z) is the phase. "The result lies in the range [-π, π]"3.
  • JavaScript. There is no complex type. The solution has functions on arrays of two numbers. Math.hypot gives the absolute value and Math.atan2 gives the phase.
  • TypeScript. The same functions as JavaScript, with the type [number, number].
  • Java. There is no complex type in the standard library. The solution defines a record Complex(double re, double im) with the methods plus, times, div, abs and phase. Math.hypot "Returns sqrt(x2 +y2) without intermediate overflow or underflow"4.
  • C#. System.Numerics.Complex has the operators and the properties Magnitude and Phase. Phase "Gets the phase of a complex number"5.
  • Go. complex(re, im) makes a complex128, and real and imag get the parts back. cmplx.Abs is the absolute value. "Phase returns the phase (also called the argument) of x. The returned value is in the range [-Pi, Pi]."6
  • Rust. The standard library has no complex type, so the solution defines a struct and implements the traits Add, Mul and Div for it. The crate num-complex has a complete type.
  • C. CMPLX(re, im) makes a double complex. creal and cimag get the parts, and cabs and carg give the absolute value and the phase.
  • C++. std::complex<double> has the operators, and std::abs and std::arg give the absolute value and the phase.
  • Bash. Bash arithmetic has only integers, so one awk program computes the 8 numbers and prints them.

The Python function:

import cmath


def complex_arithmetic(a, b):
    z, w = complex(*a), complex(*b)
    s, p, q = z + w, z * w, z / w
    return [s.real, s.imag, p.real, p.imag, q.real, q.imag, abs(z), cmath.phase(z)]


print(complex_arithmetic([3, 4], [1, -2]))
z = 3 + 4j
print(z - (1 - 2j), -z, z.conjugate(), 1 / z)
Output
[4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122]
(2+6j) (-3-4j) (3-4j) (0.12-0.16j)

The second line shows the other operations of the Rosetta Code task: subtraction, negation, the conjugate and the reciprocal. The Go type complex128 has the same operators:

package main

import (
	"fmt"
	"math/cmplx"
)

func main() {
	z, w := complex(3, 4), complex(1, -2)
	fmt.Println(z+w, z*w, z/w)
	fmt.Println(real(z), imag(z), cmplx.Abs(z), cmplx.Phase(z))
	fmt.Println(cmplx.Conj(z), -z, 1/z)
}
Output
(4+2i) (11-2i) (-1+2i)
3 4 5 0.9272952180016122
(3-4i) (-3-4i) (0.12-0.16i)

In a language with no complex type, the division is the hard part. The formula with c * c + d * d can overflow when the parts are large, although the quotient is small. A good library prevents this. For the C operator /, "complex division is not allowed to overflow intermediate results"7. Your own division can scale the numbers: divide by the larger part of the divisor first, so no intermediate value is larger than necessary. The JavaScript functions:

function div([a, b], [c, d]) {
  if (Math.abs(c) >= Math.abs(d)) {
    const r = d / c;
    const t = c + d * r;
    return [(a + b * r) / t, (b - a * r) / t];
  }
  const r = c / d;
  const t = c * r + d;
  return [(a * r + b) / t, (b * r - a) / t];
}

console.log(div([3, 4], [1, -2]));
console.log(div([1e150, 1e150], [1e155, 1e155]));
console.log(Math.hypot(1e200, 1e200), Math.atan2(4, 3));
Output
[ -1, 2 ]
[ 0.000009999999999999999, 0 ]
1.414213562373095e+200 0.9272952180016122

r is the ratio of the smaller part of the divisor to the larger part, so its size is at most 1. The second quotient is 0.00001 with a rounding error in the last digit, as the large-divisor case shows. Math.hypot computes the absolute value with the same care.

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • textbook: (3 + 4i) and (1 - 2i), with small whole-number results.
  • rosetta: the numbers 1 + i and 3.14159 + 1.25i of the Rosetta Code task.
  • real-only: two real numbers. The results are the real results, with imaginary parts 0.
  • imaginary-unit: i times i is -1, and the phase of i is π/2.
  • negative-real: the phase of -2 is π, the end of the range.
  • zero: the first number is 0. The product, the quotient, the absolute value and the phase are 0.
  • negative-phase: 1 - i is below the real axis, so its phase is negative, -π/4.
  • imaginary-divisor: the divisor 2i has the real part 0, so the scaled division takes its second branch.
  • large-divisor: (1e150 + 1e150i) / (1e155 + 1e155i) is 1e-5. The simple formula computes c * c as 1e310, which overflows to infinity.

Pitfalls

  • The simple formulas overflow. c * c + d * d in the division and a * a + b * b in the absolute value overflow for large parts. The results are then 0 or infinity, with no error:

This code runs but gives a wrong answer on purpose.

function naiveDiv([a, b], [c, d]) {
  const den = c * c + d * d;
  return [(a * c + b * d) / den, (b * c - a * d) / den];
}

console.log(naiveDiv([1e150, 1e150], [1e155, 1e155]));
console.log(Math.sqrt(1e200 * 1e200 + 1e200 * 1e200));
Output
[ 0, 0 ]
Infinity

The quotient is 1e-5, not 0, and the absolute value is about 1.414e200. Use a scaled division and Math.hypot, as in the solutions.

  • The sign of zero changes the phase. On the negative real axis, the phase is π or -π, and the sign of the imaginary part decides. In Python, "The sign of the result is the same as the sign of z.imag, even when z.imag is zero"3. The conjugate of -1 + 0i has the imaginary part -0.0:

This code runs but gives a wrong answer on purpose.

import cmath

z = complex(-1, 0)
print(cmath.phase(z), cmath.phase(z.conjugate()))
print(z.conjugate(), z == z.conjugate())
Output
3.141592653589793 -3.141592653589793
(-1-0j) True

The two numbers are equal, but their phases are different. If the code needs one value on the negative real axis, change -0.0 to 0.0 first.

  • Division by zero gives no error. In Python, z / 0j raises ZeroDivisionError. In C, C++, Go and C#, the result has infinite or NaN parts, and the program continues. For .NET, "Mathematical operations with complex numbers that are invalid or that overflow the range of the Double data type do not throw an exception"5. Check the divisor first if 0 is possible.
  • Exact comparison of results. The parts are floats, so a result is often not exact. For the rosetta case, the real part of the product is 1.8915899999999999, not 1.89159. Compare with a tolerance, as the tests do.
  • The C++ std::norm is not the absolute value. std::norm(z) is the square of the absolute value. Use std::abs for the distance from 0.
  • The output formats differ. Python prints (3+4j), Go prints (3+4i) and C++ prints (3,4). Print the two parts yourself when a program reads the output.

The C type double complex in a short program. The operator / scales, so the large case is correct:

#include <complex.h>
#include <stdio.h>

int main(void) {
    double complex z = CMPLX(3, 4), w = CMPLX(1, -2);
    double complex q = z / w;
    printf("%g %g %g %g\n", creal(q), cimag(q), cabs(z), carg(z));
    double complex big = CMPLX(1e150, 1e150) / CMPLX(1e155, 1e155);
    printf("%g %g\n", creal(big), cimag(big));
    return 0;
}
Output
-1 2 5 0.927295
1e-05 0

Code

The build runs the native tests of each language in a pinned toolchain.

complexarith.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

import cmath


def complex_arithmetic(a: list[float], b: list[float]) -> list[float]:
    """Return the sum, the product and the quotient of a and b, then abs(a) and phase(a).

    a and b are pairs [re, im]. Each complex result gives two numbers, the
    real part and the imaginary part. b must not be 0.
    """
    z, w = complex(*a), complex(*b)
    s, p, q = z + w, z * w, z / w
    return [s.real, s.imag, p.real, p.imag, q.real, q.imag, abs(z), cmath.phase(z)]
test_complexarith.py 36 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

import math

import pytest

from complexarith import complex_arithmetic

CASES = [
    ("textbook", [3.0, 4.0], [1.0, -2.0], [4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122]),
    ("rosetta", [1.0, 1.0], [3.14159, 1.25], [4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483]),
    ("real-only", [6.0, 0.0], [3.0, 0.0], [9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0]),
    ("imaginary-unit", [0.0, 1.0], [0.0, 1.0], [0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966]),
    ("negative-real", [-2.0, 0.0], [1.0, 0.0], [-1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793]),
    ("zero", [0.0, 0.0], [2.0, -3.0], [2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
    ("negative-phase", [1.0, -1.0], [-1.0, -1.0], [0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483]),
    ("imaginary-divisor", [2.0, 4.0], [0.0, 2.0], [2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904]),
    ("large-divisor", [1e+150, 1e+150], [1e+155, 1e+155], [1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483]),
]


def close(got, want):
    return math.isclose(got, want, rel_tol=1e-12, abs_tol=1e-9)


@pytest.mark.parametrize(("name", "a", "b", "want"), CASES, ids=[c[0] for c in CASES])
def test_complex_arithmetic(name, a, b, want):
    got = complex_arithmetic(a, b)
    assert len(got) == 8
    assert all(close(g, w) for g, w in zip(got, want)), got


def test_divide_by_zero_raises():
    with pytest.raises(ZeroDivisionError):
        complex_arithmetic([1, 1], [0, 0])
complexarith.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

#ifndef COMPLEX_ARITHMETIC_HPP
#define COMPLEX_ARITHMETIC_HPP

#include <array>
#include <complex>

// Returns the sum, the product and the quotient of a and b, then abs(a) and
// phase(a), as 8 numbers. a and b are pairs {re, im}.
inline std::array<double, 8> complex_arithmetic(std::array<double, 2> a, std::array<double, 2> b) {
    const std::complex<double> z{a[0], a[1]};
    const std::complex<double> w{b[0], b[1]};
    const auto s = z + w;
    const auto p = z * w;
    const auto q = z / w;
    return {s.real(), s.imag(), p.real(), p.imag(), q.real(), q.imag(), std::abs(z), std::arg(z)};
}

#endif
test_complexarith.cpp 53 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

#include <algorithm>
#include <array>
#include <cmath>
#include <cstdio>

#include "complexarith.hpp"

namespace {

struct test_case {
    const char* name;
    std::array<double, 2> a, b;
    std::array<double, 8> want;
};

const test_case cases[] = {
    {"textbook", {3.0, 4.0}, {1.0, -2.0}, {4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122}},
    {"rosetta", {1.0, 1.0}, {3.14159, 1.25}, {4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483}},
    {"real-only", {6.0, 0.0}, {3.0, 0.0}, {9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0}},
    {"imaginary-unit", {0.0, 1.0}, {0.0, 1.0}, {0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966}},
    {"negative-real", {-2.0, 0.0}, {1.0, 0.0}, {-1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793}},
    {"zero", {0.0, 0.0}, {2.0, -3.0}, {2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}},
    {"negative-phase", {1.0, -1.0}, {-1.0, -1.0}, {0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483}},
    {"imaginary-divisor", {2.0, 4.0}, {0.0, 2.0}, {2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904}},
    {"large-divisor", {1e+150, 1e+150}, {1e+155, 1e+155}, {1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483}},
};

bool close_to(double got, double want) {
    return std::abs(got - want) <= std::max(1e-9, 1e-12 * std::abs(want));
}

}  // namespace

int main() {
    int failures = 0;
    for (const auto& c : cases) {
        const auto got = complex_arithmetic(c.a, c.b);
        for (std::size_t k = 0; k < got.size(); ++k) {
            if (!close_to(got[k], c.want[k])) {
                std::printf("FAIL %s: item %zu = %.17g\n", c.name, k, got[k]);
                ++failures;
            }
        }
    }
    if (failures != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
ComplexArith.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

/** Complex number arithmetic. Java has no complex type, so this file defines one. */
public final class ComplexArith {
    private ComplexArith() {}

    /** A complex number with a real part and an imaginary part. */
    public record Complex(double re, double im) {
        public Complex plus(Complex w) {
            return new Complex(re + w.re, im + w.im);
        }

        public Complex times(Complex w) {
            return new Complex(re * w.re - im * w.im, re * w.im + im * w.re);
        }

        /** Divides by the larger part of w first, so the formula cannot overflow. */
        public Complex div(Complex w) {
            if (Math.abs(w.re) >= Math.abs(w.im)) {
                double r = w.im / w.re;
                double t = w.re + w.im * r;
                return new Complex((re + im * r) / t, (im - re * r) / t);
            }
            double r = w.re / w.im;
            double t = w.re * r + w.im;
            return new Complex((re * r + im) / t, (im * r - re) / t);
        }

        public double abs() {
            return Math.hypot(re, im);
        }

        public double phase() {
            return Math.atan2(im, re);
        }
    }

    /** Returns {sum, product, quotient, abs(a), phase(a)} as 8 numbers. a and b are {re, im}. */
    public static double[] complexArithmetic(double[] a, double[] b) {
        Complex z = new Complex(a[0], a[1]);
        Complex w = new Complex(b[0], b[1]);
        Complex s = z.plus(w);
        Complex p = z.times(w);
        Complex q = z.div(w);
        return new double[] {s.re(), s.im(), p.re(), p.im(), q.re(), q.im(), z.abs(), z.phase()};
    }
}
ComplexArithTest.java 46 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class ComplexArithTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("textbook", new double[]{3.0, 4.0}, new double[]{1.0, -2.0}, new double[]{4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122}),
                Arguments.of("rosetta", new double[]{1.0, 1.0}, new double[]{3.14159, 1.25}, new double[]{4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483}),
                Arguments.of("real-only", new double[]{6.0, 0.0}, new double[]{3.0, 0.0}, new double[]{9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0}),
                Arguments.of("imaginary-unit", new double[]{0.0, 1.0}, new double[]{0.0, 1.0}, new double[]{0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966}),
                Arguments.of("negative-real", new double[]{-2.0, 0.0}, new double[]{1.0, 0.0}, new double[]{-1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793}),
                Arguments.of("zero", new double[]{0.0, 0.0}, new double[]{2.0, -3.0}, new double[]{2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}),
                Arguments.of("negative-phase", new double[]{1.0, -1.0}, new double[]{-1.0, -1.0}, new double[]{0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483}),
                Arguments.of("imaginary-divisor", new double[]{2.0, 4.0}, new double[]{0.0, 2.0}, new double[]{2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904}),
                Arguments.of("large-divisor", new double[]{1e+150, 1e+150}, new double[]{1e+155, 1e+155}, new double[]{1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483})
        );
    }

    static boolean close(double got, double want) {
        return Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void complexArithmetic(String name, double[] a, double[] b, double[] want) {
        double[] got = ComplexArith.complexArithmetic(a, b);
        assertEquals(8, got.length);
        for (int i = 0; i < 8; i++) {
            assertTrue(close(got[i], want[i]), "item " + i + " = " + got[i]);
        }
    }

    @Test
    void recordEquality() {
        assertEquals(new ComplexArith.Complex(-1, 0), new ComplexArith.Complex(0, 1).times(new ComplexArith.Complex(0, 1)));
    }
}
complexarith.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

#include "complexarith.h"

#include <complex.h>

// The operator / on double complex does not overflow in intermediate results.
void complex_arithmetic(const double a[2], const double b[2], double out[8]) {
    double complex z = CMPLX(a[0], a[1]);
    double complex w = CMPLX(b[0], b[1]);
    double complex s = z + w, p = z * w, q = z / w;
    out[0] = creal(s);
    out[1] = cimag(s);
    out[2] = creal(p);
    out[3] = cimag(p);
    out[4] = creal(q);
    out[5] = cimag(q);
    out[6] = cabs(z);
    out[7] = carg(z);
}
complexarith.h 11 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

#ifndef COMPLEX_ARITHMETIC_H
#define COMPLEX_ARITHMETIC_H

// Sets out to the sum, the product and the quotient of a and b, then abs(a)
// and phase(a), as 8 numbers. a and b are pairs {re, im}.
void complex_arithmetic(const double a[2], const double b[2], double out[8]);

#endif
test_complexarith.c 49 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

#include "complexarith.h"

#include <math.h>
#include <stdio.h>
#include <stdlib.h>

struct test_case {
    const char *name;
    double a[2], b[2], want[8];
};

static const struct test_case cases[] = {
    {"textbook", {3.0, 4.0}, {1.0, -2.0}, {4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122}},
    {"rosetta", {1.0, 1.0}, {3.14159, 1.25}, {4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483}},
    {"real-only", {6.0, 0.0}, {3.0, 0.0}, {9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0}},
    {"imaginary-unit", {0.0, 1.0}, {0.0, 1.0}, {0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966}},
    {"negative-real", {-2.0, 0.0}, {1.0, 0.0}, {-1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793}},
    {"zero", {0.0, 0.0}, {2.0, -3.0}, {2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}},
    {"negative-phase", {1.0, -1.0}, {-1.0, -1.0}, {0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483}},
    {"imaginary-divisor", {2.0, 4.0}, {0.0, 2.0}, {2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904}},
    {"large-divisor", {1e+150, 1e+150}, {1e+155, 1e+155}, {1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483}},
};

static int close_to(double got, double want) {
    return fabs(got - want) <= fmax(1e-9, 1e-12 * fabs(want));
}

int main(void) {
    int failures = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        double got[8];
        complex_arithmetic(c->a, c->b, got);
        for (int k = 0; k < 8; k++) {
            if (!close_to(got[k], c->want[k])) {
                printf("FAIL %s: item %d = %.17g\n", c->name, k, got[k]);
                failures++;
            }
        }
    }
    if (failures != 0) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
ComplexArith.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

using System.Numerics;

/// <summary>Complex number arithmetic with System.Numerics.Complex.</summary>
public static class ComplexArith
{
    /// <summary>Returns {sum, product, quotient, abs(a), phase(a)} as 8 numbers. a and b are {re, im}.</summary>
    public static double[] ComplexArithmetic(double[] a, double[] b)
    {
        var z = new Complex(a[0], a[1]);
        var w = new Complex(b[0], b[1]);
        Complex s = z + w, p = z * w, q = z / w;
        return [s.Real, s.Imaginary, p.Real, p.Imaginary, q.Real, q.Imaginary, z.Magnitude, z.Phase];
    }
}
ComplexArithTests.cs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

using System;
using Xunit;

public sealed class ComplexArithTests
{
    public static TheoryData<string, double[], double[], double[]> Cases => new()
    {
        { "textbook", new double[] { 3.0, 4.0 }, new double[] { 1.0, -2.0 }, new double[] { 4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122 } },
        { "rosetta", new double[] { 1.0, 1.0 }, new double[] { 3.14159, 1.25 }, new double[] { 4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483 } },
        { "real-only", new double[] { 6.0, 0.0 }, new double[] { 3.0, 0.0 }, new double[] { 9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0 } },
        { "imaginary-unit", new double[] { 0.0, 1.0 }, new double[] { 0.0, 1.0 }, new double[] { 0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966 } },
        { "negative-real", new double[] { -2.0, 0.0 }, new double[] { 1.0, 0.0 }, new double[] { -1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793 } },
        { "zero", new double[] { 0.0, 0.0 }, new double[] { 2.0, -3.0 }, new double[] { 2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 } },
        { "negative-phase", new double[] { 1.0, -1.0 }, new double[] { -1.0, -1.0 }, new double[] { 0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483 } },
        { "imaginary-divisor", new double[] { 2.0, 4.0 }, new double[] { 0.0, 2.0 }, new double[] { 2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904 } },
        { "large-divisor", new double[] { 1e+150, 1e+150 }, new double[] { 1e+155, 1e+155 }, new double[] { 1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483 } },
    };

    private static bool Close(double got, double want) =>
        Math.Abs(got - want) <= Math.Max(1e-9, 1e-12 * Math.Abs(want));

    [Theory]
    [MemberData(nameof(Cases))]
    public void ComplexArithmetic(string name, double[] a, double[] b, double[] want)
    {
        Assert.NotNull(name);
        double[] got = ComplexArith.ComplexArithmetic(a, b);
        Assert.Equal(8, got.Length);
        for (int i = 0; i < 8; i++)
        {
            Assert.True(Close(got[i], want[i]), $"item {i} = {got[i]}");
        }
    }
}
complexarith.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

// JavaScript has no complex type, so a complex number is an array [re, im].

/** Returns the sum of two complex numbers [re, im]. */
export function add([a, b], [c, d]) {
  return [a + c, b + d];
}

/** Returns the product of two complex numbers. */
export function mul([a, b], [c, d]) {
  return [a * c - b * d, a * d + b * c];
}

/**
 * Returns the quotient of two complex numbers. It divides by the larger part
 * of the divisor first, so c * c + d * d is never computed and cannot overflow.
 */
export function div([a, b], [c, d]) {
  if (Math.abs(c) >= Math.abs(d)) {
    const r = d / c;
    const t = c + d * r;
    return [(a + b * r) / t, (b - a * r) / t];
  }
  const r = c / d;
  const t = c * r + d;
  return [(a * r + b) / t, (b * r - a) / t];
}

/** Returns [sum, product, quotient, abs(a), phase(a)] as 8 numbers. */
export function complexArithmetic(a, b) {
  return [...add(a, b), ...mul(a, b), ...div(a, b), Math.hypot(a[0], a[1]), Math.atan2(a[1], a[0])];
}
complexarith.test.js 29 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { complexArithmetic } from "./complexarith.js";

const cases = [
  ["textbook", [3, 4], [1, -2], [4, 2, 11, -2, -1, 2, 5, 0.9272952180016122]],
  ["rosetta", [1, 1], [3.14159, 1.25], [4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483]],
  ["real-only", [6, 0], [3, 0], [9, 0, 18, 0, 2, 0, 6, 0]],
  ["imaginary-unit", [0, 1], [0, 1], [0, 2, -1, 0, 1, 0, 1, 1.5707963267948966]],
  ["negative-real", [-2, 0], [1, 0], [-1, 0, -2, 0, -2, 0, 2, 3.141592653589793]],
  ["zero", [0, 0], [2, -3], [2, -3, 0, 0, 0, 0, 0, 0]],
  ["negative-phase", [1, -1], [-1, -1], [0, -2, -2, 0, 0, 1, 1.4142135623730951, -0.7853981633974483]],
  ["imaginary-divisor", [2, 4], [0, 2], [2, 6, -8, 4, 2, -1, 4.47213595499958, 1.1071487177940904]],
  ["large-divisor", [1e+150, 1e+150], [1e+155, 1e+155], [1.00001e+155, 1.00001e+155, 0, 2e+305, 9.999999999999999e-06, 0, 1.414213562373095e+150, 0.7853981633974483]],
];

const close = (got, want) => Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));

for (const [name, a, b, want] of cases) {
  test(name, () => {
    const got = complexArithmetic(a, b);
    assert.equal(got.length, 8);
    got.forEach((g, i) => assert.ok(close(g, want[i]), `item ${i} = ${g}`));
  });
}
complexarith.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

// TypeScript has no complex type, so a complex number is a pair [re, im].

/** A complex number as [real part, imaginary part]. */
export type Complex = readonly [number, number];

/** Returns the sum of two complex numbers. */
export function add([a, b]: Complex, [c, d]: Complex): [number, number] {
  return [a + c, b + d];
}

/** Returns the product of two complex numbers. */
export function mul([a, b]: Complex, [c, d]: Complex): [number, number] {
  return [a * c - b * d, a * d + b * c];
}

/**
 * Returns the quotient of two complex numbers. It divides by the larger part
 * of the divisor first, so c * c + d * d is never computed and cannot overflow.
 */
export function div([a, b]: Complex, [c, d]: Complex): [number, number] {
  if (Math.abs(c) >= Math.abs(d)) {
    const r = d / c;
    const t = c + d * r;
    return [(a + b * r) / t, (b - a * r) / t];
  }
  const r = c / d;
  const t = c * r + d;
  return [(a * r + b) / t, (b * r - a) / t];
}

/** Returns [sum, product, quotient, abs(a), phase(a)] as 8 numbers. */
export function complexArithmetic(a: Complex, b: Complex): number[] {
  return [...add(a, b), ...mul(a, b), ...div(a, b), Math.hypot(a[0], a[1]), Math.atan2(a[1], a[0])];
}
complexarith.test.ts 30 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

import assert from "node:assert/strict";
import { test } from "node:test";

import { type Complex, complexArithmetic } from "./complexarith.ts";

const cases: [string, Complex, Complex, number[]][] = [
  ["textbook", [3, 4], [1, -2], [4, 2, 11, -2, -1, 2, 5, 0.9272952180016122]],
  ["rosetta", [1, 1], [3.14159, 1.25], [4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483]],
  ["real-only", [6, 0], [3, 0], [9, 0, 18, 0, 2, 0, 6, 0]],
  ["imaginary-unit", [0, 1], [0, 1], [0, 2, -1, 0, 1, 0, 1, 1.5707963267948966]],
  ["negative-real", [-2, 0], [1, 0], [-1, 0, -2, 0, -2, 0, 2, 3.141592653589793]],
  ["zero", [0, 0], [2, -3], [2, -3, 0, 0, 0, 0, 0, 0]],
  ["negative-phase", [1, -1], [-1, -1], [0, -2, -2, 0, 0, 1, 1.4142135623730951, -0.7853981633974483]],
  ["imaginary-divisor", [2, 4], [0, 2], [2, 6, -8, 4, 2, -1, 4.47213595499958, 1.1071487177940904]],
  ["large-divisor", [1e+150, 1e+150], [1e+155, 1e+155], [1.00001e+155, 1.00001e+155, 0, 2e+305, 9.999999999999999e-06, 0, 1.414213562373095e+150, 0.7853981633974483]],
];

const close = (got: number, want: number): boolean =>
  Math.abs(got - want) <= Math.max(1e-9, 1e-12 * Math.abs(want));

for (const [name, a, b, want] of cases) {
  test(name, () => {
    const got = complexArithmetic(a, b);
    assert.equal(got.length, 8);
    got.forEach((g, i) => assert.ok(close(g, want[i]!), `item ${i} = ${g}`));
  });
}
complexarith.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

// Package complexarith does complex number arithmetic with the built-in
// type complex128.
package complexarith

import "math/cmplx"

// ComplexArithmetic returns the sum, the product and the quotient of a and b,
// then abs(a) and phase(a), as 8 numbers. a and b are pairs {re, im}.
func ComplexArithmetic(a, b []float64) []float64 {
	z, w := complex(a[0], a[1]), complex(b[0], b[1])
	s, p, q := z+w, z*w, z/w
	return []float64{real(s), imag(s), real(p), imag(p), real(q), imag(q), cmplx.Abs(z), cmplx.Phase(z)}
}
complexarith_test.go 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

package complexarith

import (
	"math"
	"testing"
)

var cases = []struct {
	name string
	a, b []float64
	want []float64
}{
	{"textbook", []float64{3.0, 4.0}, []float64{1.0, -2.0}, []float64{4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122}},
	{"rosetta", []float64{1.0, 1.0}, []float64{3.14159, 1.25}, []float64{4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483}},
	{"real-only", []float64{6.0, 0.0}, []float64{3.0, 0.0}, []float64{9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0}},
	{"imaginary-unit", []float64{0.0, 1.0}, []float64{0.0, 1.0}, []float64{0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966}},
	{"negative-real", []float64{-2.0, 0.0}, []float64{1.0, 0.0}, []float64{-1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793}},
	{"zero", []float64{0.0, 0.0}, []float64{2.0, -3.0}, []float64{2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0}},
	{"negative-phase", []float64{1.0, -1.0}, []float64{-1.0, -1.0}, []float64{0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483}},
	{"imaginary-divisor", []float64{2.0, 4.0}, []float64{0.0, 2.0}, []float64{2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904}},
	{"large-divisor", []float64{1e+150, 1e+150}, []float64{1e+155, 1e+155}, []float64{1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483}},
}

func close(got, want float64) bool {
	return math.Abs(got-want) <= math.Max(1e-9, 1e-12*math.Abs(want))
}

func TestComplexArithmetic(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			got := ComplexArithmetic(c.a, c.b)
			if len(got) != 8 {
				t.Fatalf("got %d numbers", len(got))
			}
			for i := range got {
				if !close(got[i], c.want[i]) {
					t.Fatalf("item %d = %v, want %v", i, got[i], c.want[i])
				}
			}
		})
	}
}
complexarith.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

use std::ops::{Add, Div, Mul};

/// A complex number. The standard library has no complex type; the crate
/// num-complex has a complete one.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Complex {
    pub re: f64,
    pub im: f64,
}

impl Add for Complex {
    type Output = Complex;
    fn add(self, w: Complex) -> Complex {
        Complex { re: self.re + w.re, im: self.im + w.im }
    }
}

impl Mul for Complex {
    type Output = Complex;
    fn mul(self, w: Complex) -> Complex {
        Complex { re: self.re * w.re - self.im * w.im, im: self.re * w.im + self.im * w.re }
    }
}

impl Div for Complex {
    type Output = Complex;
    /// Divides by the larger part of w first, so the formula cannot overflow.
    fn div(self, w: Complex) -> Complex {
        let (a, b, c, d) = (self.re, self.im, w.re, w.im);
        if c.abs() >= d.abs() {
            let r = d / c;
            let t = c + d * r;
            Complex { re: (a + b * r) / t, im: (b - a * r) / t }
        } else {
            let r = c / d;
            let t = c * r + d;
            Complex { re: (a * r + b) / t, im: (b * r - a) / t }
        }
    }
}

impl Complex {
    pub fn abs(self) -> f64 {
        self.re.hypot(self.im)
    }

    pub fn phase(self) -> f64 {
        self.im.atan2(self.re)
    }
}

/// Returns the sum, the product and the quotient of a and b, then abs(a) and
/// phase(a), as 8 numbers. a and b are pairs [re, im].
pub fn complex_arithmetic(a: &[f64], b: &[f64]) -> [f64; 8] {
    let z = Complex { re: a[0], im: a[1] };
    let w = Complex { re: b[0], im: b[1] };
    let (s, p, q) = (z + w, z * w, z / w);
    [s.re, s.im, p.re, p.im, q.re, q.im, z.abs(), z.phase()]
}
tests/complexarith_test.rs 36 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

use algo_do_complex_number_arithmetic::{complex_arithmetic, Complex};

const CASES: &[(&str, &[f64], &[f64], &[f64])] = &[
    ("textbook", &[3.0, 4.0], &[1.0, -2.0], &[4.0, 2.0, 11.0, -2.0, -1.0, 2.0, 5.0, 0.9272952180016122]),
    ("rosetta", &[1.0, 1.0], &[3.14159, 1.25], &[4.14159, 2.25, 1.8915899999999999, 4.39159, 0.38414593243590134, 0.16546321590504276, 1.4142135623730951, 0.7853981633974483]),
    ("real-only", &[6.0, 0.0], &[3.0, 0.0], &[9.0, 0.0, 18.0, 0.0, 2.0, 0.0, 6.0, 0.0]),
    ("imaginary-unit", &[0.0, 1.0], &[0.0, 1.0], &[0.0, 2.0, -1.0, 0.0, 1.0, 0.0, 1.0, 1.5707963267948966]),
    ("negative-real", &[-2.0, 0.0], &[1.0, 0.0], &[-1.0, 0.0, -2.0, 0.0, -2.0, 0.0, 2.0, 3.141592653589793]),
    ("zero", &[0.0, 0.0], &[2.0, -3.0], &[2.0, -3.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]),
    ("negative-phase", &[1.0, -1.0], &[-1.0, -1.0], &[0.0, -2.0, -2.0, 0.0, 0.0, 1.0, 1.4142135623730951, -0.7853981633974483]),
    ("imaginary-divisor", &[2.0, 4.0], &[0.0, 2.0], &[2.0, 6.0, -8.0, 4.0, 2.0, -1.0, 4.47213595499958, 1.1071487177940904]),
    ("large-divisor", &[1e+150, 1e+150], &[1e+155, 1e+155], &[1.00001e+155, 1.00001e+155, 0.0, 2e+305, 9.999999999999999e-06, 0.0, 1.414213562373095e+150, 0.7853981633974483]),
];

fn close(got: f64, want: f64) -> bool {
    (got - want).abs() <= f64::max(1e-9, 1e-12 * want.abs())
}

#[test]
fn cases() {
    for &(name, a, b, want) in CASES {
        let got = complex_arithmetic(a, b);
        for (i, (g, w)) in got.iter().zip(want).enumerate() {
            assert!(close(*g, *w), "{name}: item {i} = {g}");
        }
    }
}

#[test]
fn i_squared() {
    let i = Complex { re: 0.0, im: 1.0 };
    assert_eq!(i * i, Complex { re: -1.0, im: 0.0 });
}
complexarith.shI0RawGitHub
#!/usr/bin/env bash
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

# complex_arithmetic A_RE A_IM B_RE B_IM
# Prints the sum, the product and the quotient of a and b, then abs(a) and
# phase(a): 8 numbers on one line. Bash arithmetic has only integers, so awk
# does the floating-point work. The division divides by the larger part of b
# first, so it cannot overflow.
complex_arithmetic() {
  awk -v a="$1" -v b="$2" -v c="$3" -v d="$4" '
  function abs(x) { return x < 0 ? -x : x }
  BEGIN {
    if (c == 0 && d == 0) { print "division by zero" > "/dev/stderr"; exit 1 }
    if (abs(c) >= abs(d)) {
      r = d / c; t = c + d * r
      qr = (a + b * r) / t; qi = (b - a * r) / t
    } else {
      r = c / d; t = c * r + d
      qr = (a * r + b) / t; qi = (b * r - a) / t
    }
    # abs(a) scales by the larger part, so the squares cannot overflow.
    m = abs(a) > abs(b) ? abs(a) : abs(b)
    len = m == 0 ? 0 : m * sqrt((a / m) ^ 2 + (b / m) ^ 2)
    printf "%.17g %.17g %.17g %.17g %.17g %.17g %.17g %.17g\n", a + c, b + d, a * c - b * d, a * d + b * c, qr, qi, len, atan2(b, a)
  }'
}
test_complexarith.bats 32 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/do-complex-number-arithmetic/.

setup() {
  source "$BATS_TEST_DIRNAME/complexarith.sh"
}

# close GOT WANT: each has 8 numbers, separated by spaces.
close() {
  awk -v g="$1" -v w="$2" 'BEGIN {
    n = split(g, x, " "); m = split(w, y, " ")
    if (n != 8 || m != 8) exit 1
    for (i = 1; i <= 8; i++) {
      e = x[i] - y[i]; if (e < 0) e = -e
      t = y[i] < 0 ? -y[i] : y[i]; t = t * 1e-12; if (t < 1e-9) t = 1e-9
      if (e > t) exit 1
    }
  }'
}

@test "textbook" { run complex_arithmetic 3 4 1 -2; [ "$status" -eq 0 ]; close "$output" "4 2 11 -2 -1 2 5 0.9272952180016122"; }
@test "rosetta" { run complex_arithmetic 1 1 3.14159 1.25; [ "$status" -eq 0 ]; close "$output" "4.14159 2.25 1.8915899999999999 4.39159 0.38414593243590134 0.16546321590504276 1.4142135623730951 0.7853981633974483"; }
@test "real-only" { run complex_arithmetic 6 0 3 0; [ "$status" -eq 0 ]; close "$output" "9 0 18 0 2 0 6 0"; }
@test "imaginary-unit" { run complex_arithmetic 0 1 0 1; [ "$status" -eq 0 ]; close "$output" "0 2 -1 0 1 0 1 1.5707963267948966"; }
@test "negative-real" { run complex_arithmetic -2 0 1 0; [ "$status" -eq 0 ]; close "$output" "-1 0 -2 0 -2 0 2 3.141592653589793"; }
@test "zero" { run complex_arithmetic 0 0 2 -3; [ "$status" -eq 0 ]; close "$output" "2 -3 0 0 0 0 0 0"; }
@test "negative-phase" { run complex_arithmetic 1 -1 -1 -1; [ "$status" -eq 0 ]; close "$output" "0 -2 -2 0 0 1 1.4142135623730951 -0.7853981633974483"; }
@test "imaginary-divisor" { run complex_arithmetic 2 4 0 2; [ "$status" -eq 0 ]; close "$output" "2 6 -8 4 2 -1 4.47213595499958 1.1071487177940904"; }
@test "large-divisor" { run complex_arithmetic 1e+150 1e+150 1e+155 1e+155; [ "$status" -eq 0 ]; close "$output" "1.00001e+155 1.00001e+155 0 2e+305 9.999999999999999e-06 0 1.414213562373095e+150 0.7853981633974483"; }

@test "divide-by-zero" { run complex_arithmetic 1 1 0 0; [ "$status" -eq 1 ]; }

References

  1. Rosetta Code, Arithmetic/Complex (task text, from acmeism/RosettaCodeData), task text
  2. Wikipedia, Complex number, Complex conjugate, absolute value, argument and division
  3. The Python Standard Library, cmath, phase
  4. Java SE 25 API, Class Math, hypot(double, double)
  5. Complex Struct, .NET API reference, Properties; Remarks
  6. Go standard library, math/cmplx, func Phase
  7. cppreference.com, Arithmetic operators (C), Multiplicative operators, complex division

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)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source