Numbers

Angles and roots of unity

cos(π/5) is (1 + √5)/4. cos(2π/7) is a root of 8x³ + 4x² − 4x − 1. Every cosine and sine of a rational multiple of π is an algebraic number, and the library gives it exactly, without ever using π.

Roots of unity and cyclotomic polynomials

The n-th roots of unity are the n solutions of zⁿ = 1, the points e^(2πik/n) evenly spaced on the unit circle. Each one is primitive of some order d dividing n, and the primitive d-th roots are exactly the roots of the cyclotomic polynomial Φ_d, which has integer coefficients and is irreducible. So

xⁿ − 1 = Π_(d | n) Φ_d(x), Φ₁ = x − 1, Φ₂ = x + 1, Φ₄ = x² + 1, Φ₁₂ = x⁴ − x² + 1

and Φₙ is found by dividing xⁿ − 1 by the Φ_d of its smaller divisors. Its degree is φ(n), Euler's totient. The coefficients are usually 0 and ±1; Φ₁₀₅ is the first with a 2 in it.

The n-th roots of unity

Cosines without π

Write c = cos θ. Then cos(nθ) = Tₙ(c), with Tₙ the Chebyshev polynomial (T₀ = 1, T₁ = x, Tₙ₊₁ = 2xTₙ − Tₙ₋₁). For θ = 2πj/n that gives Tₙ(c) = 1, which only says c is one of the cosines cos(2πj/n). To get the right one without π, the library uses two facts:

  • Φₙ is palindromic, so x^(−φ(n)/2)·Φₙ(x) is a polynomial in x + 1/x = 2cos θ. That polynomial, with 2c substituted, is the minimal polynomial of cos(2π/n), of degree φ(n)/2.
  • Its roots are cos(2πj/n) for the j between 0 and n/2 that are coprime to n, and cosine decreases there. So the k-th largest root is the k-th such j.

So isolating the real roots (Sturm), sorting them, and counting picks the value exactly. sin(πr) is cos(π(1/2 − r)) and tan is their quotient.

When there is a radical form

Gauss showed that cos(2π/n) can be written with square roots alone exactly when φ(n) is a power of 2, which is why a regular 17-gon can be drawn with ruler and compass but a 7-gon cannot. format finds the forms of degree 2 and 4: cos(π/5) = (1 + √5)/4, cos(π/8) = √(2 + √2)/2, sin(π/12) = (√6 − √2)/4. A nested radical √(A + B√d) is denested into √u ± √v whenever A² − B²d is a square. Higher degrees print as certified digits.

In code

import { cosPi, sinPi, tanPi, rootOfUnity, rootsOfUnity, cyclotomic, format } from "@ratmath/algebraic";
format(cosPi("1/5"));          // "(1 + √5)/4"
format(sinPi("1/12"));         // "(√6 − √2)/4"
cosPi("2/7").poly;             // [-1n, -4n, 4n, 8n]
format(rootOfUnity(8, 3));     // "−√2/2 + i√2/2"
cyclotomic(12);                // [1n, 0n, -1n, 0n, 1n]
Try itEdit the code and run it with @ratmath/algebraic and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.
Ctrl/⌘ + Enter runs