Complex rationals
A complex rational is with and fractions. They are closed under the four operations, so arithmetic on them is exact, with no rounding anywhere.
Writing one
import { complex, Complex } from "@ratmath/complex";
complex("3 - 4i"); // from text
complex(3, -4); // from two parts, each anything Core reads
complex(["1/2", "0.#3"]); // 1/2 + 1/3 i
complex("(1 + 2i)/(3 - i)"); // text may be an expression: 1/10 + 7/10i
complex("(1 + i)^8"); // 16
complex(0.1); // 1/10: a decimal number means the decimal it prints as
Text is exact arithmetic on numbers in Core's notation (1/2, 0.25, 0.#3 for a repeating decimal, 1..1/2 for a mixed number), the letter i, + - * /, ^ with a whole-number exponent, and parentheses. 3/4i reads as , the way it is written by hand.
Arithmetic
const z = complex("3 + 4i");
String(z.add("1 - i")); // "4 + 3i"
String(z.mul("1/2 + i")); // "-5/2 + 5i"
String(z.div("1 - 2i")); // "-1 + 2i"
String(z.inv()); // "3/25 - 4/25i"
String(z.pow(-2)); // "-7/625 - 24/625i"
String(z.conj()); // "3 - 4i"
String(z.norm()); // "25": |z|², always rational
String(z.exactModulus()); // "5": |z| when it is rational, else null
z.equals("3 + 4i"); // true: equality is exact
Every method takes its argument in any of the forms complex reads. The parts are Core Rationals at z.re and z.im. Division by zero throws a ComplexError with code: "division-by-zero".
Why the norm and not the modulus
The modulus is usually irrational: . Its square, the norm , is always rational and is multiplicative, . So the exact layer works with the norm, and the modulus is an enclosure (see Polar form) except when it happens to be rational, which is exactly when is a rational Pythagorean triple.
Exact square roots
Writing with gives and , with the sign of that of . So is a complex rational exactly when is rational and both of those are squares of rationals:
complex("3 + 4i").exactSqrt().map(String); // ["2 + i", "-2 - i"]
complex("-5 - 12i").exactSqrt().map(String); // ["2 - 3i", "-2 + 3i"]
complex("-4").exactSqrt().map(String); // ["2i", "-2i"]
complex("2").exactSqrt(); // null: use sqrt() for an enclosure
As a field
CQ is the field as a RatMath field object (add, mul, inv, zero, one and the rest), which is what linalg matrices and structures polynomials take when their entries are complex. Its sign is 0 for zero and 1 otherwise, because the complex numbers cannot be ordered: if were positive or negative, would be positive.
@ratmath/complex and Core's Rational in scope. The last line's value is shown; PRINT(…) adds lines, TEX(…) typesets math.