RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Exact and higher mathematics

Rational trigonometry

Quadrance and spread instead of distance and angle, over the rationals and finite fields: the five main laws, conics, exact rotations, projective and universal hyperbolic geometry, chromogeometry and exact geometric predicates.

import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
53 classes468 functions and methods586 of 639 documented426 runnable examples

Overview

Rational-first geometry. N. J. Wildberger's Rational Trigonometry (Divine Proportions, 2005) is the baseline here: quadrance and spread instead of distance and angle, exact over any field, with floats only at the boundary.

It builds on riptide_algebra, whose ScalarField fields (RationalField, PrimeField, AlgebraicField) and RtPlane (the five laws, solvers, spread polynomials) it re-exports. It extends them as follows:

AreaTypes
FieldsQ (ordered \mathbb{Q}), OrderedAlgebraic, QuadraticExtension (\mathbb{Q}(\sqrt{d}), F_{p^{2}}), RealQuadraticField (exactly ordered)
Any metric, any dimensionVec, Mat, SymmetricForm (quadrance, spread, cross, twist, reflections), Triangle (feeds RtPlane's laws and solvers)
More lawsquadruple quad formula, Ptolemy, Brahmagupta without roots, quadrilateral quadrea, projective laws
Plane, conicsLine (metric-general perpendiculars), Centres, Conic (rational parametrisation, tangents, polars)
Rotations, motionsPythagorean triples and quadruples, spherePoint, RtQuaternion, Hurwitz, AffineMap, RigidMotion, ProjectiveMap, crossRatio
Universal geometryProjectivePlane (hyperbolic, elliptic), Chromogeometry, RedSpacetime
Robustness, boundaryPredicates, FloatPredicates (filtered + exact), FloatBoundary (bounded conversions, sensor input)
GPU tier, connectorsIVec3, IMat3, octahedralGroup, CubicLattice, FixedPointFormat, ExactLatticeState / RenderSnapshot / FeedbackGuard, ModuleKind, Module, Docking, Assembly
PolytopesregularPolygon, Polyhedron, Platonic (\mathbb{Q} and \mathbb{Q}(\sqrt{5}))
SpeedFastTriangle (integer path)
Matrix trigonometryGram (spreads, k-spreads incl. The solid spread, line–subspace and dihedral spreads as Gram-minor ratios, Triple spread as a Gram determinant), MetricMatrixTrig (wedge and B-vector-product spreads, Cayley rotations of any metric), SpreadPolynomials (O(\log n) values, spread periods over \mathbb{Z}/p), ChromoMatrices
ReflectionsReflection, ReflectionDecomposition (Cartan–Dieudonné constructively, edge pivots and slides as exact reflection chains, rotation-parameter addition), DehnScreen
Ratio backendsFieldRatio: package:riptide_math's RatioBackend over any field and metric, run through the same law suite as the float and int64 backends

The laws are checked exactly on thousands of random cases over \mathbb{Q}, \mathbb{Z}/7, \mathbb{Z}/101, \mathbb{Z}/65521, \mathbb{Z}/(2^{31} - 1), \mathbb{Q}(\sqrt{2}) and F_{101^{2}}, in the blue, red, green and random metrics. The suite also covers projective laws, chromogeometry theorems, the float boundary bounds (checked against 200-bit BigFloat), polyhedra, lattices and connectors.

Also exported here

Functions and constants

Functions

ulpfunction
double ulp(double x)

The unit in the last place of x: the spacing of doubles at |x|, 2^{e - 52} for a normal |x| in [2^{e}, 2^{e + 1}) and 2^{-1074} for zero and subnormals. ulp(1.0) is 2^{-52}. Infinity and NaN give infinity.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The gap between neighbouring doubles at x.
  for (final x in [1.0, 1000.0, 1e16, 0.1]) print('ulp($x) = ${ulp(x)}');
  print('1e16 + 1 == 1e16: ${1e16 + 1 == 1e16}  (1 is below half an ulp there)');
}
Output
ulp(1.0) = 2.220446049250313e-16
ulp(1000.0) = 1.1368683772161603e-13
ulp(10000000000000000.0) = 2.0
ulp(0.1) = 1.3877787807814457e-17
1e16 + 1 == 1e16: true  (1 is below half an ulp there)
Vec<T>? unitCirclePoint<T>(ScalarField<T> f, T t)

The point (\frac{1 - t^{2}}{1 + t^{2}}, \frac{2t}{1 + t^{2}}) of the blue unit circle x^{2} + y^{2} = 1, exact in f; the rational replacement for (\cos \theta, \sin \theta), with t classically \tan(\frac{\theta}{2}). Every point but (-1, 0) arises from exactly one t. Null when 1 + t^{2} = 0, which happens in \mathbb{Z}/p with p \equiv 1 \bmod 4.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Every rational point on the unit circle comes from a rational t.
  final pts = <List<Object>>[];
  for (final t in [rat(0), rat(1, 3), rat(1, 2), rat(1), rat(2), rat(-1, 2)]) {
    final p = unitCirclePoint(Q, t)!;
    print('t = $t: (${p.x}, ${p.y}), x² + y² = ${p.dot(p)}');
    pts.add([p.x.toDouble(), p.y.toDouble(), '$t']);
  }
}
Output
t = 0: (1, 0), x² + y² = 1
t = 1/3: (4/5, 3/5), x² + y² = 1
t = 1/2: (3/5, 4/5), x² + y² = 1
t = 1: (0, 1), x² + y² = 1
t = 2: (-3/5, 4/5), x² + y² = 1
t = -1/2: (3/5, -4/5), x² + y² = 1
Vec<T>? redUnitCirclePoint<T>(ScalarField<T> f, T t)

The point (\frac{1 + t^{2}}{1 - t^{2}}, \frac{2t}{1 - t^{2}}) of the red unit circle x^{2} - y^{2} = 1 (a rectangular hyperbola), exact in

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Rational points on x² − y² = 1: the rational boosts of 1+1 relativity.
  for (final t in [rat(0), rat(1, 2), rat(1, 3)]) {
    final p = redUnitCirclePoint(Q, t)!;
    print('t = $t: $p, x² − y² = ${p[0] * p[0] - p[1] * p[1]}');
  }
  print('t = 1 (light speed): ${redUnitCirclePoint(Q, rat(1))}');
}
Output
t = 0: [1, 0], x² − y² = 1
t = 1/2: [5/3, 4/3], x² − y² = 1
t = 1/3: [5/4, 3/4], x² − y² = 1
t = 1 (light speed): null
Vec<T>? greenUnitCirclePoint<T>(ScalarField<T> f, T t)

The point (t, \frac{1}{2t}) of the green unit circle 2xy = 1, exact in f. Null when t = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  for (final t in [rat(1), rat(2), rat(-1, 4)]) {
    final p = greenUnitCirclePoint(Q, t)!;
    print('t = $t: $p, 2xy = ${rat(2) * p[0] * p[1]}');
  }
}
Output
t = 1: [1, 1/2], 2xy = 1
t = 2: [2, 1/4], 2xy = 1
t = -1/4: [-1/4, -2], 2xy = 1
nonSquareModfunction
int nonSquareMod(PrimeField f)

The smallest n \ge 2 that is not a square in \mathbb{Z}/p (a quadratic non-residue), so that QuadraticExtension(f, nonSquareMod(f)) is the field F_{p^{2}} with p^{2} elements. Example: 3 for p = 7, 2 for p = 13. The prime must be odd: in \mathbb{Z}/2 every element is a square and the search never ends.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The smallest non-square mod p, used to build the field with p² elements.
  for (final p in [7, 13, 17, 23]) print('p = $p: ${nonSquareMod(PrimeField(p))}');
}
Output
p = 7: 3
p = 13: 2
p = 17: 3
p = 23: 5
ratfunction
Rational rat(Object n, [int d = 1])

The rational n/d, a shorthand for tests and examples: rat(3, 4) is \frac{3}{4} and rat(5) is 5.

n may be an int, a BigInt, a Rational or a string such as '3/4' or '0.25' (parsed exactly, so rat('0.1') is exactly \frac{1}{10}); the result is then divided by d. A double or any other type throws ArgumentError, an unparsable string throws FormatException, and d = 0 throws.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('rat(3)        = ${rat(3)}');
  print('rat(3, 4)     = ${rat(3, 4)}');
  print('rat("22/7")   = ${rat('22/7')}');
  print('sum           = ${rat(1, 3) + rat(1, 6)}');
}
Output
rat(3)        = 3
rat(3, 4)     = 3/4
rat("22/7")   = 22/7
sum           = 1/2
goldenRatiofunction
Quad<Rational> goldenRatio(RealQuadraticField q5)

The golden ratio \varphi = \frac{1 + \sqrt{5}}{2} as an exact element of q5, which must be \mathbb{Q}(\sqrt{5}) (RealQuadraticField.of(5)); any other d throws ArgumentError. \varphi^{2} = \varphi + 1 holds exactly, and the spreads of the regular pentagon lie in \mathbb{Q}(\sqrt{5}).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final q5 = RealQuadraticField.of(5);
  final phi = goldenRatio(q5);
  print('φ = $phi ≈ ${q5.toDouble(phi)}');
  print('φ² = ${q5.mul(phi, phi)}');
  print('φ² − φ − 1 = ${q5.sub(q5.sub(q5.mul(phi, phi), phi), q5.one)}');
}
Output
φ = (1/2 + 1/2√d) ≈ 1.618033988749895
φ² = (3/2 + 1/2√d)
φ² − φ − 1 = (0 + 0√d)
List<IMat3> octahedralGroup({bool properOnly = false})

The 48 signed permutation matrices: the full octahedral group O_{h}, the point group of the cubic lattices. With properOnly, only the 24 rotations (\det + 1).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The 48 signed permutation matrices, and the 24 rotations among them.
  final all = octahedralGroup(), rot = octahedralGroup(properOnly: true);
  print('|O_h| = ${all.length}, rotations ${rot.length}');
  print('all orthogonal: ${all.every((m) => m.isOrthogonal)}');
  // Every rotation maps the cube's vertex set to itself.
  final cube = LatticePolyhedra.cube().toSet();
  print('rotations preserve the cube: ${rot.every((g) => cube.containsAll(cube.map(g.apply)))}');
}
Output
|O_h| = 48, rotations 24
all orthogonal: true
rotations preserve the cube: true
T quadrupleQuad<T>(ScalarField<T> f, T a, T b, T c, T d)

The quadruple quad residual ((a + b + c + d)^{2} - 2(a^{2} + b^{2} + c^{2} + d^{2}))^{2} - 64\mathrm{abcd} over f: zero when a, b, c, d are the quadrances Q(A_{1}A_{2}), Q(A_{2}A_{3}), Q(A_{3}A_{4}), Q(A_{1}A_{4}) of four collinear points (Wildberger, Divine Proportions). For points 0, 1, 3, 6 on a line, (1, 4, 9, 36) gives 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Four collinear points 0, 1, 3, 6: Q₁₂ = 1, Q₂₃ = 4, Q₃₄ = 9, Q₁₄ = 36.
  print('collinear: ${quadrupleQuad(Q, rat(1), rat(4), rat(9), rat(36))}');
  print('not:       ${quadrupleQuad(Q, rat(1), rat(4), rat(9), rat(30))}');
}
Output
collinear: 0
not:       -65520
ptolemyfunction
T ptolemy<T>(ScalarField<T> f, T q12, T q13, T q14, T q23, T q24, T q34)

Ptolemy's theorem in rational form: four points A_{1}\cdots A_{4} lie on a circle (or a line) ⇔ A(Q_{12}Q_{34}, Q_{13}Q_{24}, Q_{14}Q_{23}) = 0, with A Archimedes' function RtPlane.archimedes and Q_{ij} = Q(A_{i}A_{j}). Returns that value, so zero means concyclic.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Four points on a circle satisfy Ptolemy's relation; here, the corners of a 3 × 4 rectangle.
  final r = ptolemy(Q, rat(9), rat(25), rat(16), rat(16), rat(25), rat(9));
  print('Ptolemy residual for a cyclic quadrilateral: $r');
}
Output
Ptolemy residual for a cyclic quadrilateral: 0
brahmaguptafunction
T brahmagupta<T>(ScalarField<T> f, T quadrea, T q1, T q2, T q3, T q4)

Brahmagupta's formula exactly: a cyclic quadrilateral with consecutive side quadrances Q_{1}\cdots Q_{4} and quadrea \mathcal{A} (= 16 \cdot \mathrm{area}^{2}) satisfies (\mathcal{A} + (Q_{1} + Q_{2} - Q_{3} - Q_{4})^{2} - 4Q_{1}Q_{2} - 4Q_{3}Q_{4})^{2} = 64Q_{1}Q_{2}Q_{3}Q_{4}. Returns the residual, left side minus right, so zero means the identity holds. It covers convex and crossed cyclic quadrilaterals at once.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // A cyclic quadrilateral: the 3-4-5 rectangle has quadrances 9, 16, 9, 16 and area 12.
  final a = quadrilateralQuadrea(Q, rat(9), rat(16), rat(9), rat(16), rat(25), rat(25));
  print('quadrilateral quadrea: $a (16 × 12² = ${16 * 144})');
}
Output
quadrilateral quadrea: 2304 (16 × 12² = 2304)
T quadrilateralQuadrea<T>(ScalarField<T> f, T q1, T q2, T q3, T q4, T p, T r)

The quadrea of any quadrilateral A_{1}A_{2}A_{3}A_{4} from its consecutive side quadrances Q_{1}\cdots Q_{4} and its diagonal quadrances P = Q(A_{1}A_{3}), R = Q(A_{2}A_{4}): 4PR - (Q_{1} - Q_{2} + Q_{3} - Q_{4})^{2} (Bretschneider's formula with every root removed). Equals 16 \cdot \mathrm{area}^{2} for the blue form, and 4 \cdot \det(M) \cdot (d_{1} \wedge d_{2})^{2} for a planar form with matrix M and diagonal vectors d_{1}, d_{2}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The unit square: sides 1, diagonals 2; quadrea 16·area² = 16.
  print('square: ${quadrilateralQuadrea(Q, rat(1), rat(1), rat(1), rat(1), rat(2), rat(2))}');
  // A 2 × 3 rectangle: area 6.
  print('2×3 rectangle: ${quadrilateralQuadrea(Q, rat(4), rat(9), rat(4), rat(9), rat(13), rat(13))} = 16·36 = ${16 * 36}');
}
Output
square: 16
2×3 rectangle: 576 = 16·36 = 576
qvfunction
Vec<Rational> qv(List<Object> xs)

A vector over Q from ints, BigInts, Rationals or strings like '3/4', e.g. qv([1, '1/2', -3]).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final u = qv([1, 2]), v = qv(['1/2', 3]);
  print('u = $u, v = $v');
  print('u + v = ${u + v}');
  print('u · v = ${u.dot(v)}');
  print('3u = ${u.scale(rat(3))}');
}
Output
u = [1, 2], v = [1/2, 3]
u + v = [3/2, 5]
u · v = 13/2
3u = [3, 6]
fvfunction
Vec<int> fv(PrimeField f, List<int> xs)

A vector over \mathbb{Z}/p from ints, reduced mod p: fv(PrimeField(7), [9, -1]) is [2, 6].

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Vectors over ℤ/p: the same geometry in a finite field.
  final f = PrimeField(13);
  final u = fv(f, [3, 4]), v = fv(f, [-4, 3]);
  print('u = $u, v = $v');
  print('blue quadrance of u: ${SymmetricForm.blue(f).norm(u)}  (25 mod 13)');
  print('u·v = ${u.dot(v)} (perpendicular)');
}
Output
u = [3, 4], v = [9, 3]
blue quadrance of u: 12  (25 mod 13)
u·v = 0 (perpendicular)
detfunction
T det<T>(List<Vec<T>> vs)

The determinant of the square matrix whose rows are the vectors vs. For three 3-D points in homogeneous coordinates it is zero exactly when they are collinear. Throws RangeError when vs is empty and StateError when the matrix is not square.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  print('det of (1,2), (3,4) = ${det([qv([1, 2]), qv([3, 4])])}');
  print('det of the unit cube vectors = ${det([qv([1, 0, 0]), qv([0, 1, 0]), qv([0, 0, 1])])}');
}
Output
det of (1,2), (3,4) = -2
det of the unit cube vectors = 1
lineSpreadfunction
T lineSpread<T>(SymmetricForm<T> form, Line<T> l, Line<T> m)

The spread between the lines l and m in the planar metric form: 0 for parallel lines, 1 for perpendicular ones. Throws StateError when either line is null in form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The spread between y = 0 and y = 2x: 4/5, from the line coefficients alone.
  final l = Line.join(qv([0, 0]), qv([1, 0])), m = Line.join(qv([0, 0]), qv([1, 2]));
  print('blue: ${lineSpread(SymmetricForm.blue(Q), l, m)}');
  print('red:  ${lineSpread(SymmetricForm.red(Q), l, m)}');
}
Output
blue: 4/5
red:  4/3
List<Vec<T>> regularPolygon<T>(ScalarField<T> f, T c, T s, int n)

The n points R^{k} (1, 0), k = 0 \cdots n - 1, over the field f, where R is the rotation with cosine c and sine s.

For a regular n-gon pass the cosine and sine of \frac{2\pi}{n}, which must lie in f: over \mathbb{Q}(\sqrt{3}) the hexagon uses c = \frac{1}{2}, s = \frac{\sqrt{3}}{2}. Throws ArgumentError unless c^{2} + s^{2} = 1. The point (1, 0) is always returned, so n \le 1 gives that single point.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // A square: the rotation with cosine 0 and sine 1 is exact over the rationals.
  final sq = regularPolygon(Q, rat(0), rat(1), 4);
  print('square: $sq');
  final blue = SymmetricForm.blue(Q);
  print('side quadrance: ${blue.quadrance(sq[0], sq[1])}');
}
Output
square: [[1, 0], [0, 1], [-1, 0], [0, -1]]
side quadrance: 2
RigidMotion<T> composeReflections<T>(SymmetricForm<T> form, List<Reflection<T>> rs)

The single rigid motion of form equal to the reflections rs applied in order, the first in the list first. An empty list gives the identity. Throws ArgumentError when a reflection is not an isometry of form (for example, one built for a different metric).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Two reflections in lines through the origin make a rotation.
  final blue = SymmetricForm.blue(Q);
  final m = composeReflections(blue, [Reflection(blue, qv([0, 1])), Reflection(blue, qv([-1, 2]))]);
  print('linear part:\n${m.linear}');
  print('proper: ${m.isProper}');
}
Output
linear part:
3/5 -4/5
4/5 3/5
proper: true
rotation2function
Mat<T> rotation2<T>(ScalarField<T> f, T a, T b)

The blue (Euclidean) planar rotation \begin{bmatrix}a & -b \\ b & a\end{bmatrix} for the point (a, b) of the unit circle: it turns (1, 0) to (a, b), counterclockwise for b > 0. Classically a = \cos \theta and b = \sin \theta, but no angle is needed.

Throws ArgumentError unless a^{2} + b^{2} = 1 exactly in f.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The rotation for the rational point (5/13, 12/13) on the unit circle.
  final r = rotation2(Q, rat(5, 13), rat(12, 13));
  print(r);
  print('(13, 0) ↦ ${r.apply(qv([13, 0]))}');
}
Output
5/13 -12/13
12/13 5/13
(13, 0) ↦ [5, 12]
(BigInt, BigInt, BigInt) pythagoreanTriple(BigInt m, BigInt n)

The Pythagorean triple (m^{2} - n^{2}, 2mn, m^{2} + n^{2}) of Euclid's formula: (m^{2} - n^{2})^{2} + (2mn)^{2} = (m^{2} + n^{2})^{2}. Every primitive triple arises, up to swapping the legs, from coprime m > n > 0 of opposite parity.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  for (final (m, n) in [(2, 1), (3, 2), (4, 1), (5, 2)]) {
    final (a, b, c) = pythagoreanTriple(BigInt.from(m), BigInt.from(n));
    print('m = $m, n = $n: $a² + $b² = $c²  (${a * a + b * b == c * c})');
  }
}
Output
m = 2, n = 1: 3² + 4² = 5²  (true)
m = 3, n = 2: 5² + 12² = 13²  (true)
m = 4, n = 1: 15² + 8² = 17²  (true)
m = 5, n = 2: 21² + 20² = 29²  (true)
Mat<Rational> rotationFromTriple(int m, int n)

The exact rotation over Q of the triple from (m, n) (see pythagoreanTriple): rotation2 with a = \frac{m^{2} - n^{2}}{m^{2} + n^{2}} and b = \frac{2mn}{m^{2} + n^{2}} (classically \cos \theta and \sin \theta). For example (2, 1) gives \begin{bmatrix}\frac{3}{5} & -\frac{4}{5} \\ \frac{4}{5} & \frac{3}{5}\end{bmatrix}. Throws ArgumentError when m = n = 0 (zero denominator).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The triple 3-4-5 gives the exact rotation [[3/5, −4/5], [4/5, 3/5]].
  final rot = rotationFromTriple(2, 1);
  print('rotation:\n$rot');
  var p = qv([1, 0]);
  for (var i = 0; i < 100; i++) p = rot.apply(p);
  print('after 100 exact turns, x² + y² = ${p.dot(p)}');
  print('denominator of x has ${p.x.denominator.toString().length} digits');
}
Output
rotation:
3/5 -4/5
4/5 3/5
after 100 exact turns, x² + y² = 1
denominator of x has 70 digits
(BigInt, BigInt, BigInt, BigInt) pythagoreanQuadruple(BigInt a, BigInt b, BigInt c, BigInt d)

The Pythagorean quadruple (a^{2} + b^{2} - c^{2} - d^{2}, 2(\operatorname{ad} + bc), 2(bd - ac), a^{2} + b^{2} + c^{2} + d^{2}) from the quaternion a + bi + cj + dk: the first three entries square-sum to the square of the last. They are the image of e_{1} = (1, 0, 0) under the quaternion's rotation (RtQuaternion.rotate), scaled by its norm to integers.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final (a, b, c, d) = pythagoreanQuadruple(BigInt.one, BigInt.one, BigInt.one, BigInt.zero);
  print('($a)² + ($b)² + ($c)² = ($d)²: ${a * a + b * b + c * c == d * d}');
}
Output
(1)² + (2)² + (-2)² = (3)²: true
spherePointfunction
Vec<T>? spherePoint<T>(ScalarField<T> f, T s, T t)

The point of the blue unit sphere x^{2} + y^{2} + z^{2} = 1 by inverse stereographic projection from the north pole: \frac{(2s, 2t, s^{2} + t^{2} - 1)}{s^{2} + t^{2} + 1}, with coordinates in f whenever s and t are. Every point but the north pole (0, 0, 1) arises this way. Null when s^{2} + t^{2} + 1 = 0, which can happen in \mathbb{Z}/p.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final p = spherePoint(Q, rat(1, 2), rat(1, 3))!;
  print('point: $p');
  print('on the unit sphere: ${p.dot(p) == rat(1)}');
}
Output
point: [36/49, 24/49, -23/49]
on the unit sphere: true
crossRatiofunction
T crossRatio<T>(Vec<T> a, Vec<T> b, Vec<T> c, Vec<T> d)

The cross ratio (A, B; C, D) = ([A C]{}[B D]) / ([A D]{}[B C]) of four collinear points, given homogeneously in the projective plane, where [P Q] = \det(P, Q, O) for a point O off the line.

It is a projective invariant: every ProjectiveMap keeps it, exactly. Throws ArgumentError when the points are degenerate (A = B, so no line is fixed).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  Vec<Rational> pt(int x) => qv([x, 1, 1]); // points on the line y = 1, in homogeneous coordinates
  print('cross ratio (0, 1; 2, 3) = ${crossRatio(pt(0), pt(1), pt(2), pt(3))}');
  // It is projectively invariant: map x -> 2x + 1.
  print('after x -> 2x + 1:        ${crossRatio(pt(1), pt(3), pt(5), pt(7))}');
}
Output
cross ratio (0, 1; 2, 3) = 4/3
after x -> 2x + 1:        4/3

Constants and variables

unitRoundoffconstant
const double unitRoundoff = 1.1102230246251565e-16

2^{-53} \approx 1.11 \times 10^{-16}, the unit roundoff of binary64: one correctly rounded operation has relative error at most this.

Qconstant
const OrderedRationals Q = OrderedRationals()

\mathbb{Q} with its order, the default field of this package: exact rational arithmetic with exact signs.

Classes

class

Bounded

final class Bounded

A double with a proven bound: |\text{exact} - \text{value}| \le \text{error}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A double with a certified error bound.
  final b = FloatBoundary.value(rat(1, 3));
  print('value ${b.value}, error ≤ ${b.error}, contains 0.3333333333333333: ${b.contains(0.3333333333333333)}');
}
Output
value 0.3333333333333333, error ≤ 2.7755575615628914e-17, contains 0.3333333333333333: true

Constructors

Boundedconstructor
const Bounded(this.value, this.error)

The approximation value with absolute error at most error.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const b = Bounded(1.0, 0.25);
  print('${b.contains(1.2)}, ${b.contains(1.3)}');
}
Output
true, false

Properties

valuefield
final double value

The double approximation, and the bound on its absolute error.

errorfield
final double error

The double approximation, and the bound on its absolute error.

Methods

containsmethod
bool contains(double x)

Whether x lies in the interval [value − error, value + error], so it could be the exact value.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final d = FloatBoundary.distance(rat(2));
  print('√2 ≈ ${d.value} ± ${d.error}; contains 1.4142135623730951: ${d.contains(1.4142135623730951)}');
}
Output
√2 ≈ 1.4142135623730951 ± 3.1401849173675503e-16; contains 1.4142135623730951: true
toStringmethod
String toString()
abstract final class FloatBoundary

The conversions across the float boundary: exact values out to doubles with error bounds (value, distance, angle, rapidity, vector, vector32) and measured doubles in to exact rationals (capture, bestRational, rationalRotationNear, rationalQuaternionNear).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Exact inside, doubles only at the boundary, each with an error bound.
  final q = rat(25, 9);
  print('distance of quadrance 25/9: ${FloatBoundary.distance(q)}');
}
Output
distance of quadrance 25/9: 1.6666666666666667 ± 3.7007434154171886e-16

Static

valuestaticmethod
static Bounded value(Rational r)

The rational r as the nearest double, with error \le \tfrac{1}{2} ulp of the result.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final b = FloatBoundary.value(rat(1, 10));
  print('1/10 → ${b.value}, error ≤ ${b.error}');
}
Output
1/10 → 0.1, error ≤ 6.938893903907228e-18
distancestaticmethod
static Bounded distance(Rational quadrance)

The distance \sqrt{Q} for a quadrance Q, as a double. Relative error \le 2^{-53} (from Q's rounding, halved by the root) + 2^{-53} (the root's rounding), so error \le 1.5 \cdot 2^{-53} \cdot (1 + 2^{-52}) \cdot \sqrt{Q}, reported here as 2^{-52}·value. Throws ArgumentError for a negative quadrance (which occurs in red and green geometry and has no real distance).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final d = FloatBoundary.distance(rat(2));
  print('√2 from Q = 2: ${d.value}, error ≤ ${d.error}');
}
Output
√2 from Q = 2: 1.4142135623730951, error ≤ 3.1401849173675503e-16
anglestaticmethod
static Bounded angle(Rational spread)

The angle \theta \in [0, \frac{\pi}{2}] in radians of a blue spread s = \sin^{2}\theta (a spread does not tell an angle from its supplement, so this is the acute one). The cross 1 - s is formed exactly first, so \theta = \operatorname{atan2}(\sqrt{s}, \sqrt{1 - s}) has no cancellation near s = 1: absolute error \le 2^{-52} (input roundings, condition number \sin\theta\cos\theta \le \tfrac{1}{2} per relative unit) + 2 \mathrm{ulp}(\theta) (atan2). Throws ArgumentError unless 0 \le s \le 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The spread 3/4 is the angle π/3.
  final a = FloatBoundary.angle(rat(3, 4));
  print('angle ${a.value} ± ${a.error}; π/3 = ${3.141592653589793 / 3}');
}
Output
angle 1.0471975511965976 ± 6.661338147750939e-16; π/3 = 1.0471975511965976
rapiditystaticmethod
static Bounded rapidity(Rational redSpread)

The rapidity |\Delta\eta| of a red spread s = -\sinh^{2}(\Delta\eta) \le 0 between timelike directions: \operatorname{asinh}(\sqrt{-s}), with relative error \le 4 \cdot 2^{-53} (the log-based asinh assumed ≤ 2 ulp); the reported bound is 8 \cdot 2^{-53} \cdot |\Delta\eta| + 2 ulp. Throws ArgumentError when redSpread > 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The red spread between rest and velocity 3/5 is −9/16; rapidity = asinh(3/4).
  final r = FloatBoundary.rapidity(rat(-9, 16));
  print('rapidity ${r.value} ± ${r.error}');
}
Output
rapidity 0.6931471805599453 ± 8.376829723743609e-16
vectorstaticmethod
static (Float64List, double) vector(Vec<Rational> v)

The rational vector v as doubles, each coordinate rounded to nearest, and one bound valid for every coordinate: the largest \tfrac{1}{2} ulp among them.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final (v, err) = FloatBoundary.vector(qv(['1/3', 2, '-1/10']));
  print('$v, per-coordinate error ≤ $err');
}
Output
[0.3333333333333333, 2.0, -0.1], per-coordinate error ≤ 2.220446049250313e-16
vector32staticmethod
static (Float32List, double) vector32(Vec<Rational> v)

The rational vector v as float32 for the GPU, with one error bound valid for every coordinate. Each coordinate is rounded to nearest float32, so its error is about \tfrac{1}{2} \mathrm{ulp}_{32} (2^{-24} relative); the bound returned also covers the first rounding to double. Integer coordinates of magnitude \le 2^{24} convert exactly.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final (v, err) = FloatBoundary.vector32(qv([3, 1000000, '1/3']));
  print('$v, error ≤ $err');
}
Output
[3.0, 1000000.0, 0.3333333432674408], error ≤ 9.934107508824397e-9
capturestaticmethod
static Rational capture(double x)

A measured double captured exactly as the dyadic rational it is: capture(0.1) is \frac{3602879701896397}{2^{55}}, not \frac{1}{10}. No error is added at the boundary; the sensor's own error is the caller's (use bestRational for a small denominator instead). Throws ArgumentError for NaN or infinity.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A double is a dyadic rational: capture it exactly.
  print('0.1 is exactly ${FloatBoundary.capture(0.1)}');
}
Output
0.1 is exactly 3602879701896397/36028797018963968
bestRationalstaticmethod
static Rational bestRational(double x, int maxDenominator)

The best rational approximation \frac{p}{q} of x with 1 \le q ≤ maxDenominator, from the continued fraction of x with the best semiconvergent: bestRational(π, 1000) is \frac{355}{113}. Error ≤ 1/(q·maxDenominator) for the returned q; when x is itself a fraction with small enough denominator, it is returned exactly. maxDenominator must be at least 1, and x finite (capture's ArgumentError otherwise).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  for (final d in [10, 100, 1000, 100000]) print('π with q ≤ $d: ${FloatBoundary.bestRational(3.141592653589793, d)}');
}
Output
π with q ≤ 10: 22/7
π with q ≤ 100: 311/99
π with q ≤ 1000: 355/113
π with q ≤ 100000: 312689/99532
static (Vec<Rational>, Bounded) rationalRotationNear(double theta, int maxDenominator)

An exact rational rotation near a measured angle theta (radians, |\theta| < \pi): t \approx \tan(\frac{\theta}{2}) with denominator ≤ maxDenominator (by bestRational), then the point (\frac{1 - t^{2}}{1 + t^{2}}, \frac{2t}{1 + t^{2}}), which is exactly on the unit circle. Returns that (cos, sin) pair as a vector, and a Bounded whose value is the angle 2 \operatorname{atan} t of the exact rotation and whose error bounds |\theta - 2 \operatorname{atan} t| \le 2|t - \tan(\frac{\theta}{2})| (+ the float evaluation of tan, bounded by 2 ulp). Throws ArgumentError when |\theta| \ge \pi.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // An exactly unit rational rotation close to a measured 30°.
  final (p, err) = FloatBoundary.rationalRotationNear(3.141592653589793 / 6, 100);
  print('point $p, on the unit circle: ${p.dot(p)}, angle ${err.value} ± ${err.error} (asked for ${3.141592653589793 / 6})');
}
Output
point [8733/10085, 5044/10085], on the unit circle: 1, angle 0.5237705293610381 ± 0.000184089364559048 (asked for 0.5235987755982988)
static (RtQuaternion<Rational>, double) rationalQuaternionNear(double w, double x, double y, double z, int bits)

An exact rational rotation near a measured unit quaternion (w, x, y, z): each coordinate is rounded to the nearest multiple of 2^−bits. The Euler–Rodrigues matrix of the rounded quaternion is exactly orthogonal (\det 1) whatever the rounding. Returns the rational RtQuaternion and a bound on the rotation-angle error: \le 2 \cdot \operatorname{asin}(\frac{|\Delta q|}{|q|}) \le 2.1 \cdot 2 \cdot 2^{-\mathrm{bits}} for |q| \approx 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final (q, err) = FloatBoundary.rationalQuaternionNear(0.9238795325112867, 0.3826834323650898, 0, 0, 8);
  print('q = $q, error $err');
  print('its rotation is exact: det ${q.toRotationMatrix().determinant}');
}
Output
q = (237/256, 49/128, 0, 0), error 0.01640625
its rotation is exact: det 1
enum

Colour

enum Colour

The three colours of chromogeometry: blue (Euclidean, x^{2} + y^{2}), red (x^{2} - y^{2}) and green (2xy).

Values

bluevalue
blue

Euclidean geometry, Q_{b} = x^{2} + y^{2}.

redvalue
red

Minkowski geometry with null lines along the diagonals, Q_{r} = x^{2} - y^{2}.

greenvalue
green

Minkowski geometry with null lines along the axes, Q_{g} = 2xy.

final class Chromogeometry<T>

The three geometries of the plane over a field, side by side: one SymmetricForm per Colour, and the identities that tie them together.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final c = Chromogeometry(Q);
  final u = qv([5, 2]);
  final (b, r, g) = c.quadrances(u);
  print('blue $b, red $r, green $g');
  print('blue² = red² + green²: ${b * b == r * r + g * g}');
}
Output
blue 29, red 21, green 20
blue² = red² + green²: true

Constructors

Chromogeometryconstructor
Chromogeometry(this.field)

The blue, red and green forms over field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Chromogeometry(Q);
  final v = qv([2, 1]);
  print('blue ${c.blue.norm(v)}, red ${c.red.norm(v)}, green ${c.green.norm(v)}');
}
Output
blue 5, red 3, green 4

Properties

fieldfield
final ScalarField<T> field

The field the points live in.

bluefield
final SymmetricForm<T> blue

The forms Q_{b} = x^{2} + y^{2}, Q_{r} = x^{2} - y^{2} and Q_{g} = 2xy.

redfield
final SymmetricForm<T> red

The forms Q_{b} = x^{2} + y^{2}, Q_{r} = x^{2} - y^{2} and Q_{g} = 2xy.

greenfield
final SymmetricForm<T> green

The forms Q_{b} = x^{2} + y^{2}, Q_{r} = x^{2} - y^{2} and Q_{g} = 2xy.

Methods

formmethod
SymmetricForm<T> form(Colour c)

The form of the colour c.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Chromogeometry(Q);
  for (final col in Colour.values) print('$col:\n${c.form(col).matrix}');
}
Output
Colour.blue:
1 0
0 1
Colour.red:
1 0
0 -1
Colour.green:
0 1
1 0
(T, T, T) quadrances(Vec<T> v)

The three quadrances (Q_{b}, Q_{r}, Q_{g}) of the vector v.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final (b, r, g) = Chromogeometry(Q).quadrances(qv([3, 2]));
  print('Q_b = $b, Q_r = $r, Q_g = $g; Q_b² = Q_r² + Q_g²: ${b * b == r * r + g * g}');
}
Output
Q_b = 13, Q_r = 5, Q_g = 12; Q_b² = Q_r² + Q_g²: true
T pythagoreanResidual(Vec<T> v)

Q_{b}^{2} - Q_{r}^{2} - Q_{g}^{2} for the vector v: zero for every vector, since (x^{2} + y^{2})^{2} = (x^{2} - y^{2})^{2} + (2xy)^{2}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final c = Chromogeometry(Q);
  for (final v in [qv([1, 2]), qv(['7/3', -5]), qv([0, 1])]) print('$v: ${c.pythagoreanResidual(v)}');
}
Output
[1, 2]: 0
[7/3, -5]: 0
[0, 1]: 0
T spreadResidual(Vec<T> u, Vec<T> v)

\frac{1}{s_{b}} + \frac{1}{s_{r}} + \frac{1}{s_{g}} - 2 for the lines with directions u and v: zero whenever it is defined. Throws StateError when u or v is null in some colour, and the field's division error when the lines are parallel (every spread 0).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // 1/s_b + 1/s_r + 1/s_g = 2 for any two lines that are non-null in every colour.
  final c = Chromogeometry(Q);
  print('residual: ${c.spreadResidual(qv([1, 3]), qv([2, -5]))}');
}
Output
residual: 0
Vec<T>? circumcentre(Colour c, Vec<T> a, Vec<T> b, Vec<T> d)

The circumcentre of the triangle a, b, d in the colour c (Centres.circumcentre); null for collinear vertices.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Chromogeometry(Q);
  final a = qv([0, 0]), b = qv([4, 0]), d = qv([1, 3]);
  for (final col in Colour.values) print('$col circumcentre: ${c.circumcentre(col, a, b, d)}');
}
Output
Colour.blue circumcentre: [2, 1]
Colour.red circumcentre: [2, 2]
Colour.green circumcentre: [1, 0]
Vec<T>? orthocentre(Colour c, Vec<T> a, Vec<T> b, Vec<T> d)

The orthocentre of the triangle a, b, d in the colour c (Centres.orthocentre); null for collinear vertices.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The blue, red and green orthocentres of one triangle.
  final c = Chromogeometry(Q);
  final a = qv([0, 0]), b = qv([4, 0]), d = qv([1, 3]);
  for (final col in Colour.values) print('$col orthocentre: ${c.orthocentre(col, a, b, d)}');
}
Output
Colour.blue orthocentre: [1, 1]
Colour.red orthocentre: [1, -1]
Colour.green orthocentre: [3, 3]
final class RedSpacetime<T>

Special relativity in one space dimension as red geometry, exactly. Events are (t, x) with c = 1; the red quadrance Q_{r} = \Delta t^{2} - \Delta x^{2} is the squared proper time (positive: timelike, zero: lightlike, negative: spacelike; riptide_relativity's {-}{+}{+}{+} interval is -Q_{r}). Red rotations are Lorentz boosts. A boost is rational exactly when its velocity is v = \frac{2t}{1 + t^{2}} for rational t, i.e. when (v, \frac{1}{\gamma}) is a rational point of the blue unit circle: then \gamma = \frac{1 + t^{2}}{1 - t^{2}} and \gamma v = \frac{2t}{1 - t^{2}} are rational (chromogeometry links the two colours).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // 1+1 special relativity in red geometry, exactly: a boost with parameter 1/2 has velocity 4/5.
  final st = RedSpacetime(Q);
  print('velocity of t = 1/2: ${st.velocityOfParameter(rat(1, 2))}');
  print('boost:\n${st.boost(rat(1, 2))}');
}
Output
velocity of t = 1/2: 4/5
boost:
5/3 4/3
4/3 5/3

Constructors

RedSpacetimeconstructor
RedSpacetime(this.field)

Spacetime over field, with the red form as its metric.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final st = RedSpacetime(Q);
  print('the red form:\n${st.form.matrix}');
}
Output
the red form:
1 0
0 -1

Properties

fieldfield
final ScalarField<T> field

The field coordinates and velocities live in.

formfield
final SymmetricForm<T> form

The red form Q_{r}(t, x) = t^{2} - x^{2}.

Methods

eventmethod
Vec<T> event(T t, T x)

The event at time t and position x.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final st = RedSpacetime(Q);
  final e = st.event(rat(5), rat(3));
  print('event (t, x) = $e, interval from the origin: ${st.interval(st.event(rat(0), rat(0)), e)}');
}
Output
event (t, x) = [5, 3], interval from the origin: 16
intervalmethod
T interval(Vec<T> a, Vec<T> b)

Q_{r}(A, B) = \Delta t^{2} - \Delta x^{2}, the squared proper time between the events a and b: positive for timelike, zero for lightlike, negative for spacelike separation.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Δt² − Δx²: positive timelike, zero lightlike, negative spacelike.
  final st = RedSpacetime(Q);
  final o = st.event(rat(0), rat(0));
  for (final (t, x) in [(5, 3), (2, 2), (1, 3)]) print('($t, $x): ${st.interval(o, st.event(rat(t), rat(x)))}');
}
Output
(5, 3): 16
(2, 2): 0
(1, 3): -8
boostmethod
Mat<T>? boost(T t)

The boost with parameter t (rapidity \eta = 2 \operatorname{artanh} t): \begin{bmatrix}\gamma & \gamma v \\ \gamma v & \gamma\end{bmatrix} with \gamma = \frac{1 + t^{2}}{1 - t^{2}}, \gamma v = \frac{2t}{1 - t^{2}}, acting on events (t, x); its velocity is velocityOfParameter of t. For t = \frac{1}{2} it is \begin{bmatrix}\frac{5}{3} & \frac{4}{3} \\ \frac{4}{3} & \frac{5}{3}\end{bmatrix} (v = \frac{4}{5}). Null when t^{2} = 1 (the speed of light).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The boost preserves the interval exactly.
  final st = RedSpacetime(Q);
  final b = st.boost(rat(1, 3))!;
  final e = st.event(rat(5), rat(3)), o = st.event(rat(0), rat(0));
  print('boosted event: ${b.apply(e)}');
  print('interval before ${st.interval(o, e)}, after ${st.interval(o, b.apply(e))}');
  print('t = 1: ${st.boost(rat(1))}');
}
Output
boosted event: [17/2, 15/2]
interval before 16, after 16
t = 1: null
T velocityOfParameter(T t)

The velocity v = \frac{2t}{1 + t^{2}} of the boost with parameter t. Throws the field's division error when 1 + t^{2} = 0 (possible in \mathbb{Z}/p).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final st = RedSpacetime(Q);
  for (final t in [rat(1, 2), rat(1, 3), rat(1, 7)]) print('t = $t → v = ${st.velocityOfParameter(t)}');
}
Output
t = 1/2 → v = 4/5
t = 1/3 → v = 3/5
t = 1/7 → v = 7/25
T? parameterOfVelocity(T v)

The parameter t = \frac{v}{1 + \sqrt{1 - v^{2}}} of the velocity v, so that velocityOfParameter of t is v. Null when 1 - v^{2} has exact by construction in the field, that is when the boost of v is not over the field (as for v = \frac{1}{2} over \mathbb{Q}); v = \frac{3}{5} gives t = \frac{1}{3}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final st = RedSpacetime(Q);
  print('v = 4/5 → t = ${st.parameterOfVelocity(rat(4, 5))}');
  print('v = 1/2 → ${st.parameterOfVelocity(rat(1, 2))}  (1 − v² = 3/4 is not a square)');
}
Output
v = 4/5 → t = 1/2
v = 1/2 → null  (1 − v² = 3/4 is not a square)
T addVelocities(T u, T v)

Relativistic velocity addition \frac{u + v}{1 + uv}: rational for rational velocities. Throws the field's division error when uv = -1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final st = RedSpacetime(Q);
  print('1/2 ⊕ 1/2 = ${st.addVelocities(rat(1, 2), rat(1, 2))}');
  print('9/10 ⊕ 9/10 = ${st.addVelocities(rat(9, 10), rat(9, 10))}');
  print('v ⊕ 1 = ${st.addVelocities(rat(1, 3), rat(1))}  (light stays light)');
}
Output
1/2 ⊕ 1/2 = 4/5
9/10 ⊕ 9/10 = 180/181
v ⊕ 1 = 1  (light stays light)
spreadmethod
T spread(Vec<T> u, Vec<T> w)

The red spread between two worldlines with directions u, w: s_{r} = 1 - \frac{B_{r}(u, w)^{2}}{Q_{r}(u)Q_{r}(w)}, which is -\sinh^{2}(\Delta\eta) for timelike directions with rapidity difference \Delta\eta (the classical view). For example (1, 0) and (\frac{5}{4}, \frac{3}{4}) (v = \frac{3}{5}) give -\frac{9}{16}. Throws StateError when either direction is lightlike (null).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The red spread between the worldlines at rest and at velocity 3/5.
  final st = RedSpacetime(Q);
  print('s_r = ${st.spread(qv([1, 0]), qv([5, 3]))}  (−sinh² of the rapidity difference)');
}
Output
s_r = -9/16  (−sinh² of the rapidity difference)
T gammaSquared(T v)

\gamma^{2} = \frac{1}{1 - v^{2}}: the squared time dilation for the velocity v, rational for every rational v (\gamma itself needs a square root). Throws the field's division error when v^{2} = 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final st = RedSpacetime(Q);
  for (final v in [rat(3, 5), rat(1, 2), rat(99, 100)]) print('v = $v: γ² = ${st.gammaSquared(v)}');
}
Output
v = 3/5: γ² = 25/16
v = 1/2: γ² = 4/3
v = 99/100: γ² = 10000/199
class

Conic

final class Conic<T>

The conic a x^{2} + b xy + c y^{2} + d x + e y + f = 0 over a field: an ellipse, parabola, hyperbola, or a degenerate pair of lines or point.

From one known point on the conic, parametrize reaches every other point by a rational function of a slope t, so points, tangents (tangentAt) and polars (polar) stay exact in field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // x² + y² − 25 = 0, and its tangent at (3, 4).
  final circle = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(25));
  print('circle: $circle');
  print('contains (3, 4): ${circle.contains(qv([3, 4]))}');
  print('tangent at (3, 4): ${circle.tangentAt(qv([3, 4]))}');
  // The line through (3, 4) with direction (1, 0) meets the circle again at (−3, 4).
  print('second meet: ${circle.secondMeet(qv([3, 4]), qv([1, 0]))}');
}
Output
circle: Conic(1, 0, 1, 0, 0, -25)
contains (3, 4): true
tangent at (3, 4): ⟨6 : 8 : -50⟩
second meet: [-3, 4]

Constructors

Conicconstructor
Conic(this.field, this.a, this.b, this.c, this.d, this.e, this.f)

The conic a x^{2} + b xy + c y^{2} + d x + e y + f = 0 over field. The coefficients are not checked (all zero is accepted).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // ax² + bxy + cy² + dx + ey + f = 0: the parabola y = x² is x² − y = 0.
  final p = Conic(Q, rat(1), rat(0), rat(0), rat(0), rat(-1), rat(0));
  print('conic: $p, discriminant ${p.discriminant} (0: a parabola), degenerate ${p.isDegenerate}');
}
Output
conic: Conic(1, 0, 0, 0, -1, 0), discriminant 0 (0: a parabola), degenerate false
factory Conic.circle(SymmetricForm<T> form, Vec<T> centre, T k)

The circle of quadrance k about centre in the planar metric form: the points X with B(X - C, X - C) = K. Blue: a circle; red: the rectangular hyperbola x^{2} - y^{2} = K (shifted to C); green: the hyperbola 2xy = K (Wildberger, "Chromogeometry", 2008). The blue unit circle about the origin has coefficients (1, 0, 1, 0, 0, -1).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A "circle" of quadrance 1 in each colour: a circle and two hyperbolas.
  for (final (n, f) in [('blue', SymmetricForm.blue(Q)), ('red', SymmetricForm.red(Q)), ('green', SymmetricForm.green(Q))]) {
    print('$n: ${Conic.circle(f, qv([0, 0]), rat(1))}');
  }
}
Output
blue: Conic(1, 0, 1, 0, 0, -1)
red: Conic(1, 0, -1, 0, 0, -1)
green: Conic(0, 2, 0, 0, 0, -1)

Properties

fieldfield
final ScalarField<T> field

The field the coefficients live in.

afield
final T a

The coefficients of a x^{2} + b xy + c y^{2} + d x + e y + f = 0.

bfield
final T b

The coefficients of a x^{2} + b xy + c y^{2} + d x + e y + f = 0.

cfield
final T c

The coefficients of a x^{2} + b xy + c y^{2} + d x + e y + f = 0.

dfield
final T d

The coefficients of a x^{2} + b xy + c y^{2} + d x + e y + f = 0.

efield
final T e

The coefficients of a x^{2} + b xy + c y^{2} + d x + e y + f = 0.

ffield
final T f

The coefficients of a x^{2} + b xy + c y^{2} + d x + e y + f = 0.

matrixgetter
Mat<T> get matrix

The symmetric 3 \times 3 matrix M of the projective conic x^{T} M x = 0 with x = (x, y, 1): \begin{bmatrix}a & \frac{b}{2} & \frac{d}{2} \\ \frac{b}{2} & c & \frac{e}{2} \\ \frac{d}{2} & \frac{e}{2} & f\end{bmatrix}. In characteristic 2, where 2 = 0, it throws the field's division error.

bool get isDegenerate

Whether the conic is degenerate (a pair of lines, a double line, a point or empty over the field): \det M = 0.

T get discriminant

The discriminant b^{2} - 4ac. For a non-degenerate conic over an ordered field: negative for an ellipse, zero for a parabola, positive for a hyperbola.

Methods

evaluatemethod
T evaluate(Vec<T> p)

The value a x^{2} + b xy + c y^{2} + d x + e y + f at the point p: zero exactly on the conic.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(25));
  for (final p in [qv([3, 4]), qv([0, 0]), qv([5, 5])]) print('C$p = ${c.evaluate(p)}');
}
Output
C[3, 4] = 0
C[0, 0] = -25
C[5, 5] = 25
containsmethod
bool contains(Vec<T> p)

Whether the point p lies on the conic.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(1));
  print('(3/5, 4/5): ${c.contains(qv(['3/5', '4/5']))}, (20/29, 21/29): ${c.contains(qv(['20/29', '21/29']))}, (1/2, 1/2): ${c.contains(qv(['1/2', '1/2']))}');
}
Output
(3/5, 4/5): true, (20/29, 21/29): true, (1/2, 1/2): false
T quadraticPart(Vec<T> u)

The quadratic part a u^{2} + b uv + c v^{2} at the direction u = (u, v). Zero means u is an asymptotic direction: lines in that direction meet the conic at most once.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Zero for an asymptotic direction: the hyperbola xy = 1 has asymptotes along the axes.
  final h = Conic(Q, rat(0), rat(1), rat(0), rat(0), rat(0), rat(-1));
  print('direction (1,0): ${h.quadraticPart(qv([1, 0]))}, (1,1): ${h.quadraticPart(qv([1, 1]))}');
}
Output
direction (1,0): 0, (1,1): 1
gradientmethod
Vec<T> gradient(Vec<T> p)

The gradient (2ax + by + d, bx + 2cy + e) of the conic's polynomial at p: a normal to the tangent when p is on the conic, and zero at a singular point.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(25));
  print('gradient at (3, 4): ${c.gradient(qv([3, 4]))}  (normal to the circle)');
}
Output
gradient at (3, 4): [6, 8]  (normal to the circle)
Vec<T>? secondMeet(Vec<T> p, Vec<T> u)

The second point where the line through p with direction u meets the conic, for p on the conic. \operatorname{Conic}(P + \lambda u) = \lambda(\nabla \cdot u) + \lambda^{2}q(u), so \lambda = -\frac{\nabla \cdot u}{q(u)}: a rational operation. Null for an asymptotic direction (q(u) = 0). For a tangent direction (\nabla \cdot u = 0) the result is p itself. p is not checked; off the conic the result is meaningless.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // From the rational point (−1, 0) of the unit circle, slope 1/2 gives another rational point.
  final c = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(1));
  final p = c.secondMeet(qv([-1, 0]), qv([2, 1]))!;
  print('second meet: $p, on circle: ${c.contains(p)}');
  print('tangent direction: ${c.secondMeet(qv([-1, 0]), qv([0, 1]))}');
}
Output
second meet: [3/5, 4/5], on circle: true
tangent direction: [-1, 0]
({Vec<T>? Function(T t) at, Vec<T>? atInfinity}) parametrize(Vec<T> p)

The rational parametrisation through the point p on the conic: at(t) is the secondMeet with the line of slope t, direction (1, t), and atInfinity the one with the vertical direction (t = \infty). Each is null for an asymptotic direction and p itself for the tangent direction. For the unit circle from p = (-1, 0), at(1) is (0, 1) and atInfinity is (-1, 0).

Throws ArgumentError when p is not on the conic.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Every rational point of x² + y² = 1 from one: t ↦ second meet of the line of slope t through (−1, 0).
  final c = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(1));
  final par = c.parametrize(qv([-1, 0]));
  final pts = <List<Object>>[];
  for (final t in [rat(1, 3), rat(1, 2), rat(2, 3), rat(2), rat(-1, 2)]) {
    final p = par.at(t)!;
    print('t = $t: $p');
    pts.add([p[0].toDouble(), p[1].toDouble(), '$t']);
  }
  print('t = ∞: ${par.atInfinity}');
}
Output
t = 1/3: [4/5, 3/5]
t = 1/2: [3/5, 4/5]
t = 2/3: [5/13, 12/13]
t = 2: [-3/5, 4/5]
t = -1/2: [3/5, -4/5]
t = ∞: [-1, 0]
tangentAtmethod
Line<T> tangentAt(Vec<T> p)

The tangent line at the point p on the conic: the line through p normal to the gradient. Throws ArgumentError at a singular point, where the gradient is zero. p is not checked to be on the conic.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The tangent to the parabola y = x² at (2, 4): y = 4x − 4.
  final p = Conic(Q, rat(1), rat(0), rat(0), rat(0), rat(-1), rat(0));
  final t = p.tangentAt(qv([2, 4]));
  print('tangent: $t, contains (1, 0): ${t.contains(qv([1, 0]))}');
}
Output
tangent: ⟨4 : -1 : -4⟩, contains (1, 0): true
polarmethod
Line<T> polar(Vec<T> p)

The polar line of the point p: the line with coefficients M (p, 1), and the tangent at p when p is on the conic. Throws ArgumentError when the polar is the line at infinity (as for the centre of a circle).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The polar of (5, 0) for the unit circle is x = 1/5: the chord of contact of the two tangents from (5, 0).
  final c = Conic.circle(SymmetricForm.blue(Q), qv([0, 0]), rat(1));
  print('polar of (5, 0): ${c.polar(qv([5, 0]))}');
  print('polar of (3/5, 4/5) (on the circle, so the tangent): ${c.polar(qv(['3/5', '4/5']))}');
}
Output
polar of (5, 0): ⟨5 : 0 : -1⟩
polar of (3/5, 4/5) (on the circle, so the tangent): ⟨3/5 : 4/5 : -1⟩
toStringmethod
String toString()

Conic(a, b, c, d, e, f) with the coefficients formatted by the field.

enum ModuleKind

A space-filling module shape: its connector points relative to its centre (face centres; a neighbour docked on connector c sits at centre + 2c).

Values

cubevalue
cube

A cube on \mathbb{Z}^{3}: 6 connectors (\pm1, 0, 0) and permutations.

rhombicDodecahedron

A rhombic dodecahedron on the face-centred cubic lattice (the octet truss): 12 connectors, the permutations of (\pm1, \pm1, 0).

truncatedOctahedron

A truncated octahedron on the body-centred cubic lattice: 14 connectors, 8 hexagon ones (\pm1, \pm1, \pm1) followed by 6 square ones (\pm2, 0, 0) and permutations.

Properties

List<IVec3> get connectors

The connector points relative to the centre, in a fixed order (connector i is connectors[i]); a new list each call.

latticegetter
CubicLattice get lattice

The lattice the module centres occupy (in the doubled coordinates used here).

int get contactQuadrance

The smallest quadrance between centres of two non-overlapping modules (two neighbours sharing a face): 4 for the cube, 8 for the rhombic dodecahedron, 12 for the truncated octahedron.

Set<Rational> get axisSpreads

The distinct exact spreads between connector axes, including 0 for a connector with itself: {0, 1} for the cube, \{0, \frac{3}{4}, 1\} for the rhombic dodecahedron, \{0, \frac{2}{3}, \frac{8}{9}, 1\} for the truncated octahedron.

class

Module

final class Module

A module placed at an integer centre with a lattice rotation.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Module(ModuleKind.rhombicDodecahedron, IVec3(0, 0, 0));
  print('${m.kind.connectors.length} connectors; connector 0 at ${m.connectorPoint(0)}');
}
Output
12 connectors; connector 0 at (-1, -1, 0)

Constructors

Moduleconstructor
Module(this.kind, this.centre, [this.orientation = IMat3.identity])

A module of kind centred at centre, turned by orientation (default: no rotation). Throws ArgumentError unless orientation is a lattice rotation (orthogonal with determinant +1, one of octahedralGroup(properOnly: true)); reflections are rejected.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Module(ModuleKind.cube, IVec3(2, 0, 0), IMat3([0, -1, 0, 1, 0, 0, 0, 0, 1]));
  print('direction of connector 0: ${m.direction(0)}');
}
Output
direction of connector 0: (0, -1, 0)

Properties

kindfield
final ModuleKind kind

The module's shape.

centrefield
final IVec3 centre

The centre, in the doubled integer coordinates of ModuleKind.connectors.

final IMat3 orientation

The rotation from the shape's own frame to the world frame.

int get connectorCount

The number of connectors: 6, 12 or 14.

Methods

directionmethod
IVec3 direction(int i)

The world direction of connector i: its offset from the centre after rotation, exactly. Throws RangeError for an index outside 0 … connectorCount - 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Module(ModuleKind.cube, IVec3(0, 0, 0));
  print('${[for (var i = 0; i < 6; i++) m.direction(i)]}');
}
Output
[(-1, 0, 0), (0, -1, 0), (0, 0, -1), (0, 0, 1), (0, 1, 0), (1, 0, 0)]
IVec3 connectorPoint(int i)

The world point of connector i: centre + direction(i).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Module(ModuleKind.cube, IVec3(4, 0, 0));
  print('${m.connectorPoint(0)}');
}
Output
(3, 0, 0)
int connectorAlong(IVec3 worldDirection)

The index of the connector of this module whose world direction equals worldDirection exactly, or -1 if none does. The vector must match, not only its direction: (2, 0, 0) does not find a cube's (1, 0, 0) connector.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Module(ModuleKind.cube, IVec3(0, 0, 0));
  print('along +z: ${m.connectorAlong(IVec3(0, 0, 1))}, along (1,1,0): ${m.connectorAlong(IVec3(1, 1, 0))}');
}
Output
along +z: 3, along (1,1,0): -1
class

Docking

abstract final class Docking

Docking and collision, all exact integer tests.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = Module(ModuleKind.cube, IVec3(0, 0, 0));
  final i = a.connectorAlong(IVec3(1, 0, 0));
  final b = Docking.dockOnto(a, i, ModuleKind.cube, a.connectorAlong(IVec3(-1, 0, 0)), IMat3.identity)!;
  print('docked at ${b.centre}, overlap: ${Docking.overlap(a, b)}');
}
Output
docked at (2, 0, 0), overlap: false

Static

canDockstaticmethod
static bool canDock(Module a, int i, Module b, int j)

Whether connector i of a mates connector j of b: same world point and opposite directions.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = Module(ModuleKind.cube, IVec3(0, 0, 0)), b = Module(ModuleKind.cube, IVec3(2, 0, 0));
  print('${Docking.canDock(a, a.connectorAlong(IVec3(1, 0, 0)), b, b.connectorAlong(IVec3(-1, 0, 0)))}');
  print('${Docking.canDock(a, a.connectorAlong(IVec3(0, 1, 0)), b, b.connectorAlong(IVec3(-1, 0, 0)))}');
}
Output
true
false
dockOntostaticmethod
static Module? dockOnto(Module a, int i, ModuleKind kind, int j, IMat3 orientation)

The module of kind with orientation placed so that its connector j mates connector i of a; null when the two connectors cannot face each other under that orientation (directions not exactly opposite). Throws ArgumentError if orientation is not a lattice rotation. It does not check for collisions; use Assembly.add for that.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = Module(ModuleKind.rhombicDodecahedron, IVec3(0, 0, 0));
  final i = a.connectorAlong(IVec3(1, 1, 0));
  final j = a.connectorAlong(IVec3(-1, -1, 0));
  print('neighbour centre: ${Docking.dockOnto(a, i, ModuleKind.rhombicDodecahedron, j, IMat3.identity)?.centre}');
}
Output
neighbour centre: (2, 2, 0)
overlapstaticmethod
static bool overlap(Module a, Module b)

Whether two modules of the same kind overlap: the quadrance between their centres is below the contact quadrance of a's kind (equal centres included). For modules of different kinds the answer is not meaningful.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = Module(ModuleKind.cube, IVec3(0, 0, 0));
  print('${Docking.overlap(a, Module(ModuleKind.cube, IVec3(1, 0, 0)))}, ${Docking.overlap(a, Module(ModuleKind.cube, IVec3(2, 0, 0)))}');
}
Output
true, false
final class Assembly

A set of placed modules with exact consistency checks.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final asm = Assembly();
  print('${asm.add(Module(ModuleKind.cube, IVec3(0, 0, 0)))}, ${asm.add(Module(ModuleKind.cube, IVec3(2, 0, 0)))}, ${asm.add(Module(ModuleKind.cube, IVec3(1, 0, 0)))}');
  print('modules: ${asm.modules.length}, mated pairs: ${asm.matedPairs()}');
}
Output
true, true, false
modules: 2, mated pairs: [(0, 5, 1, 0)]

Properties

modulesfield
final List<Module> modules

The placed modules in the order they were added. The list is mutable; adding to it directly skips the checks in add.

Methods

addmethod
bool add(Module m)

Adds m unless it collides with an existing module, and returns whether it was added. A collision is an equal centre (any kinds) or, for modules of the same kind, Docking.overlap; modules of different kinds at different centres are not checked against each other.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final asm = Assembly();
  for (final x in [0, 2, 4, 3]) print('cube at x = $x added: ${asm.add(Module(ModuleKind.cube, IVec3(x, 0, 0)))}');
}
Output
cube at x = 0 added: true
cube at x = 2 added: true
cube at x = 4 added: true
cube at x = 3 added: false
List<(int, int, int, int)> matedPairs()

Every pair of mated connectors, as records (a, i, b, j) meaning connector i of modules[a] mates connector j of modules[b], with a < b. It tests every pair of modules, so the cost grows with the square of their number.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final asm = Assembly();
  for (final p in [IVec3(0, 0, 0), IVec3(2, 0, 0), IVec3(0, 2, 0)]) asm.add(Module(ModuleKind.cube, p));
  print('${asm.matedPairs()}');
}
Output
[(0, 5, 1, 0), (0, 4, 2, 1)]
final class FastTriangle

The three quadrances, three spreads and the quadrea of a planar triangle with rational vertices, in the blue (Euclidean) metric, computed in integers over a common denominator.

The values equal those of Triangle over Q exactly; only the route is cheaper. Use Triangle for other fields, other metrics or more than the measures listed here.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The same measures as Triangle (blue), computed in integers for speed.
  final t = FastTriangle(qv([0, 0]), qv([4, 0]), qv([0, 3]));
  print('Q = ${t.q1}, ${t.q2}, ${t.q3}; s = ${t.s1}, ${t.s2}, ${t.s3}; quadrea ${t.quadrea}');
}
Output
Q = 25, 9, 16; s = 1, 9/25, 16/25; quadrea 576

Constructors

factory FastTriangle(Vec<Rational> a1, Vec<Rational> a2, Vec<Rational> a3)

The measures of the triangle with vertices a1, a2, a3, given as 2-D rational vectors (only the first two coordinates are read). Q_{i} is the quadrance of the side opposite A_{i} and s_{i} the spread at A_{i}, as in Triangle.

Throws StateError when two vertices coincide, where a spread is undefined. Three distinct collinear points are allowed: every spread and the quadrea are then 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final t = FastTriangle(qv(['1/2', 0]), qv([3, '1/3']), qv([1, 2]));
  final slow = Triangle(SymmetricForm.blue(Q), qv(['1/2', 0]), qv([3, '1/3']), qv([1, 2]));
  print('s1 = ${t.s1}; agrees with Triangle: ${t.s1 == slow.s1 && t.q3 == slow.q3}');
}
Output
s1 = 3364/3893; agrees with Triangle: true

Properties

q1field
final Rational q1

The quadrances Q_{1} = Q(A_{2}, A_{3}), Q_{2} = Q(A_{1}, A_{3}), Q_{3} = Q(A_{1}, A_{2}), each the squared side length opposite the vertex of the same index, and the spreads s_{1}, s_{2}, s_{3} at A_{1}, A_{2}, A_{3} (the spread between the two sides that meet there, in [0, 1]). Example: for (0, 0), (1, 0), (0, \tfrac{1}{2}) these are \frac{5}{4}, \frac{1}{4}, 1 and 1, \frac{1}{5}, \frac{4}{5}.

q2field
final Rational q2

The quadrances Q_{1} = Q(A_{2}, A_{3}), Q_{2} = Q(A_{1}, A_{3}), Q_{3} = Q(A_{1}, A_{2}), each the squared side length opposite the vertex of the same index, and the spreads s_{1}, s_{2}, s_{3} at A_{1}, A_{2}, A_{3} (the spread between the two sides that meet there, in [0, 1]). Example: for (0, 0), (1, 0), (0, \tfrac{1}{2}) these are \frac{5}{4}, \frac{1}{4}, 1 and 1, \frac{1}{5}, \frac{4}{5}.

q3field
final Rational q3

The quadrances Q_{1} = Q(A_{2}, A_{3}), Q_{2} = Q(A_{1}, A_{3}), Q_{3} = Q(A_{1}, A_{2}), each the squared side length opposite the vertex of the same index, and the spreads s_{1}, s_{2}, s_{3} at A_{1}, A_{2}, A_{3} (the spread between the two sides that meet there, in [0, 1]). Example: for (0, 0), (1, 0), (0, \tfrac{1}{2}) these are \frac{5}{4}, \frac{1}{4}, 1 and 1, \frac{1}{5}, \frac{4}{5}.

s1field
final Rational s1

The quadrances Q_{1} = Q(A_{2}, A_{3}), Q_{2} = Q(A_{1}, A_{3}), Q_{3} = Q(A_{1}, A_{2}), each the squared side length opposite the vertex of the same index, and the spreads s_{1}, s_{2}, s_{3} at A_{1}, A_{2}, A_{3} (the spread between the two sides that meet there, in [0, 1]). Example: for (0, 0), (1, 0), (0, \tfrac{1}{2}) these are \frac{5}{4}, \frac{1}{4}, 1 and 1, \frac{1}{5}, \frac{4}{5}.

s2field
final Rational s2

The quadrances Q_{1} = Q(A_{2}, A_{3}), Q_{2} = Q(A_{1}, A_{3}), Q_{3} = Q(A_{1}, A_{2}), each the squared side length opposite the vertex of the same index, and the spreads s_{1}, s_{2}, s_{3} at A_{1}, A_{2}, A_{3} (the spread between the two sides that meet there, in [0, 1]). Example: for (0, 0), (1, 0), (0, \tfrac{1}{2}) these are \frac{5}{4}, \frac{1}{4}, 1 and 1, \frac{1}{5}, \frac{4}{5}.

s3field
final Rational s3

The quadrances Q_{1} = Q(A_{2}, A_{3}), Q_{2} = Q(A_{1}, A_{3}), Q_{3} = Q(A_{1}, A_{2}), each the squared side length opposite the vertex of the same index, and the spreads s_{1}, s_{2}, s_{3} at A_{1}, A_{2}, A_{3} (the spread between the two sides that meet there, in [0, 1]). Example: for (0, 0), (1, 0), (0, \tfrac{1}{2}) these are \frac{5}{4}, \frac{1}{4}, 1 and 1, \frac{1}{5}, \frac{4}{5}.

quadreafield
final Rational quadrea

The quadrea \mathcal{A} = 16 \cdot \mathrm{area}^{2} of the triangle, computed as \frac{4w^{2}}{L^{4}} (w the integer wedge, L the common denominator); it also equals Archimedes' (Q_{1} + Q_{2} + Q_{3})^{2} - 2(Q_{1}^{2} + Q_{2}^{2} + Q_{3}^{2}). Zero exactly when the vertices are collinear.

extension

FieldOps

extension FieldOps<T> on ScalarField<T>

Derived operations available on every ScalarField: inverse, square, integer powers, sums and printing.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Derived operations on any field: here ℤ/11.
  final f = PrimeField(11);
  print('3⁻¹ = ${f.inv(3)}, 4² = ${f.square(4)}, 2¹⁰ = ${f.pow(2, 10)}, sum 1..10 = ${f.sum([for (var i = 1; i <= 10; i++) i])}');
}
Output
3⁻¹ = 4, 4² = 5, 2¹⁰ = 1, sum 1..10 = 0

Methods

invmethod
T inv(T a)

The multiplicative inverse 1/a, computed as div(one, a). Division by zero is the field's error: over Q and the quadratic extensions it throws UnsupportedError.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('ℚ: (3/7)⁻¹ = ${Q.inv(rat(3, 7))}');
  print('ℤ/13: 5⁻¹ = ${PrimeField(13).inv(5)}  (5 · 8 = 40 = 1 mod 13)');
}
Output
ℚ: (3/7)⁻¹ = 7/3
ℤ/13: 5⁻¹ = 8  (5 · 8 = 40 = 1 mod 13)
squaremethod
T square(T a)

a^{2}, the element a times itself.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('(2/3)² = ${Q.square(rat(2, 3))}, 9² in ℤ/7 = ${PrimeField(7).square(9)}');
}
Output
(2/3)² = 4/9, 9² in ℤ/7 = 4
powmethod
T pow(T a, int k)

a^{k} for any integer k, by repeated squaring (O(log |k|) multiplications). a^{0} is one (also for a = 0). For k < 0 this is \frac{1}{a^{|k|}} through inv, so a = 0 with k < 0 throws as division by zero does.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('(1/2)^10 = ${Q.pow(rat(1, 2), 10)}, (1/2)^-3 = ${Q.pow(rat(1, 2), -3)}');
  print('Fermat in ℤ/101: 7^100 = ${PrimeField(101).pow(7, 100)}');
}
Output
(1/2)^10 = 1/1024, (1/2)^-3 = 8
Fermat in ℤ/101: 7^100 = 1
summethod
T sum(Iterable<T> xs)

The sum of xs, exactly; zero for an empty iterable.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('1/1 + … + 1/6 = ${Q.sum([for (var k = 1; k <= 6; k++) rat(1, k)])}');
}
Output
1/1 + … + 1/6 = 49/20
formatmethod
String format(T a)

A readable form of the element a: 1 + 3√2 for an element of a QuadraticExtension, otherwise the element's own toString (1/3 over Q).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Q.format(rat(-3, 4))}, ${PrimeField(7).format(10)}');
}
Output
-3/4, 10
abstract interface class OrderedField<T> implements ScalarField<T>

A field with an exact order: \mathbb{Q} (Q), \mathbb{Q}(\sqrt{d}) for d > 0 (RealQuadraticField) and the real algebraic numbers (OrderedAlgebraic). The order is what Predicates and the other sign tests need: the sign of an element is decided exactly, never from a rounded double.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Exact predicates need an order: ℚ and ℚ(√d) for d > 0 provide sign and toDouble.
  final OrderedField<Rational> f = Q;
  print('sign(−2/3) = ${f.sign(rat(-2, 3))}, toDouble(1/3) = ${f.toDouble(rat(1, 3))}');
}
Output
sign(−2/3) = -1, toDouble(1/3) = 0.3333333333333333

Methods

signmethod
int sign(T a)

The exact sign of a: -1 when a < 0, 0 when a = 0, +1 when a > 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // In ℚ(√2): sign of 7 − 5√2 (≈ −0.07), decided exactly.
  final q2 = RealQuadraticField.of(2);
  print('sign(7 − 5√2) = ${q2.sign(q2.make(rat(7), rat(-5)))}, sign(3 − 2√2) = ${q2.sign(q2.make(rat(3), rat(-2)))}');
}
Output
sign(7 − 5√2) = -1, sign(3 − 2√2) = 1
toDoublemethod
double toDouble(T a)

a as a double, for leaving exact arithmetic (rendering, display). This is the one place a value is rounded; FloatBoundary gives the conversions with proven error bounds.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q5 = RealQuadraticField.of(5);
  print('φ ≈ ${q5.toDouble(goldenRatio(q5))}');
}
Output
φ ≈ 1.618033988749895
extension

OrderedOps

extension OrderedOps<T> on OrderedField<T>

Comparison on an OrderedField.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('compare(1/3, 2/7) = ${Q.compare(rat(1, 3), rat(2, 7))}');
}
Output
compare(1/3, 2/7) = 1

Methods

comparemethod
int compare(T a, T b)

The exact sign of a - b: -1 when a < b, 0 when equal, +1 when a > b (the compareTo convention, so it can be passed to List.sort as (a, b) => field.compare(a, b)).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // √2 vs 99/70: compared exactly in ℚ(√2).
  final q2 = RealQuadraticField.of(2);
  print('compare(√2, 99/70) = ${q2.compare(q2.root, q2.of(rat(99, 70)))}  (99/70 is just above √2)');
  print('compare(√2, 140/99) = ${q2.compare(q2.root, q2.of(rat(140, 99)))}');
}
Output
compare(√2, 99/70) = -1  (99/70 is just above √2)
compare(√2, 140/99) = 1
final class OrderedRationals implements OrderedField<Rational>

\mathbb{Q} with its order: riptide_algebra's RationalField plus sign and toDouble. Elements are exact Rationals; division by zero throws UnsupportedError, and sqrt returns null when the rational is not a perfect square. Use the constant Q rather than constructing one.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Q is OrderedRationals(): ℚ with its order, the default field of the package.
  print('$Q: ${Q.add(rat(1, 2), rat(1, 3))}, sign ${Q.sign(rat(-1))}');
}
Output
ℚ: 5/6, sign -1

Constructors

OrderedRationalsconstructor
const OrderedRationals()

The ordered rationals; the same field as Q.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedRationals();
  print('${f.div(rat(1), rat(3))}, same as Q: ${f.equals(f.div(rat(1), rat(3)), Q.div(rat(1), rat(3)))}');
}
Output
1/3, same as Q: true

Properties

zerogetter
Rational get zero
onegetter
Rational get one
int get characteristic

Methods

fromIntmethod
Rational fromInt(int n)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Q.fromInt(-7)}');
}
Output
-7
Rational fromRational(Rational r)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Q.fromRational(rat(5, 8))}');
}
Output
5/8
addmethod
Rational add(Rational a, Rational b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('1/10 + 2/10 = ${Q.add(rat(1, 10), rat(2, 10))}; doubles: ${0.1 + 0.2}');
}
Output
1/10 + 2/10 = 3/10; doubles: 0.30000000000000004
submethod
Rational sub(Rational a, Rational b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('3/10 − 1/10 = ${Q.sub(rat(3, 10), rat(1, 10))}; doubles: ${0.3 - 0.1}');
}
Output
3/10 − 1/10 = 1/5; doubles: 0.19999999999999998
mulmethod
Rational mul(Rational a, Rational b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('(1/10)·3 = ${Q.mul(rat(1, 10), rat(3))}; doubles: ${0.1 * 3}');
}
Output
(1/10)·3 = 3/10; doubles: 0.30000000000000004
divmethod
Rational div(Rational a, Rational b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('1/3 ÷ 1/9 = ${Q.div(rat(1, 3), rat(1, 9))}');
}
Output
1/3 ÷ 1/9 = 3
negmethod
Rational neg(Rational a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Q.neg(rat(2, 5))}');
}
Output
-2/5
isZeromethod
bool isZero(Rational a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('1/3 − 1/3 is zero: ${Q.isZero(rat(1, 3) - rat(1, 3))}; doubles 0.1 + 0.2 − 0.3 = ${0.1 + 0.2 - 0.3}');
}
Output
1/3 − 1/3 is zero: true; doubles 0.1 + 0.2 − 0.3 = 5.551115123125783e-17
equalsmethod
bool equals(Rational a, Rational b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('2/4 = 1/2: ${Q.equals(rat(2, 4), rat(1, 2))}');
}
Output
2/4 = 1/2: true
sqrtmethod
Rational? sqrt(Rational a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A rational square root when there is one, otherwise null.
  print('√(9/16) = ${Q.sqrt(rat(9, 16))}, √2 = ${Q.sqrt(rat(2))}');
}
Output
√(9/16) = 3/4, √2 = null
signmethod
int sign(Rational a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Q.sign(rat(-1, 1000000))}, ${Q.sign(rat(0))}, ${Q.sign(rat(3))}');
}
Output
-1, 0, 1
toDoublemethod
double toDouble(Rational a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('1/3 → ${Q.toDouble(rat(1, 3))}');
}
Output
1/3 → 0.3333333333333333
toStringmethod
String toString()
final class OrderedAlgebraic implements OrderedField<AlgebraicNumber>

The real algebraic numbers with their order (riptide_algebra's AlgebraicField plus sign): every real root exists, so the regular pentagon and every constructible figure have exact coordinates.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The real algebraic numbers: every real root exists exactly.
  const f = OrderedAlgebraic();
  final r2 = f.sqrt(f.fromInt(2))!;
  print('√2 ≈ ${f.toDouble(r2)} (stored exactly as a root of x² − 2), (√2)² = ${f.mul(r2, r2)}');
}
Output
√2 ≈ 1.4142135623730951 (stored exactly as a root of x² − 2), (√2)² = 2

Constructors

OrderedAlgebraicconstructor
const OrderedAlgebraic()

The ordered real algebraic numbers.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  final s = f.add(f.sqrt(f.fromInt(2))!, f.sqrt(f.fromInt(3))!);
  print('√2 + √3 ≈ ${f.toDouble(s)}, sign ${f.sign(s)}');
}
Output
√2 + √3 ≈ 3.1462643699419726, sign 1

Properties

zerogetter
AlgebraicNumber get zero
onegetter
AlgebraicNumber get one
int get characteristic

Methods

fromIntmethod
AlgebraicNumber fromInt(int n)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${const OrderedAlgebraic().fromInt(5)}');
}
Output
5
AlgebraicNumber fromRational(Rational r)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${const OrderedAlgebraic().fromRational(rat(-3, 4))}');
}
Output
-3/4
addmethod
AlgebraicNumber add(AlgebraicNumber a, AlgebraicNumber b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  final r = f.sqrt(f.fromInt(2))!;
  print('√2 + √2 ≈ ${f.toDouble(f.add(r, r))}, equals √8: ${f.equals(f.add(r, r), f.sqrt(f.fromInt(8))!)}');
}
Output
√2 + √2 ≈ 2.8284271247461903, equals √8: true
submethod
AlgebraicNumber sub(AlgebraicNumber a, AlgebraicNumber b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  final r = f.sqrt(f.fromInt(2))!;
  print('√2 − √2 = ${f.sub(r, r)}, is zero: ${f.isZero(f.sub(r, r))}');
}
Output
√2 − √2 = 0, is zero: true
mulmethod
AlgebraicNumber mul(AlgebraicNumber a, AlgebraicNumber b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  print('√2 · √3 = √6: ${f.equals(f.mul(f.sqrt(f.fromInt(2))!, f.sqrt(f.fromInt(3))!), f.sqrt(f.fromInt(6))!)}');
}
Output
√2 · √3 = √6: true
divmethod
AlgebraicNumber div(AlgebraicNumber a, AlgebraicNumber b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  final r = f.div(f.fromInt(1), f.sqrt(f.fromInt(2))!);
  print('1/√2 ≈ ${f.toDouble(r)}, squared ${f.mul(r, r)}');
}
Output
1/√2 ≈ 0.7071067811865476, squared 1/2
negmethod
AlgebraicNumber neg(AlgebraicNumber a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  print('sign of −√5: ${f.sign(f.neg(f.sqrt(f.fromInt(5))!))}');
}
Output
sign of −√5: -1
isZeromethod
bool isZero(AlgebraicNumber a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  // (√2 + √3)² − 5 − 2√6 is exactly zero.
  final s = f.add(f.sqrt(f.fromInt(2))!, f.sqrt(f.fromInt(3))!);
  final z = f.sub(f.sub(f.mul(s, s), f.fromInt(5)), f.mul(f.fromInt(2), f.sqrt(f.fromInt(6))!));
  print('zero: ${f.isZero(z)}');
}
Output
zero: true
equalsmethod
bool equals(AlgebraicNumber a, AlgebraicNumber b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  print('√(3 + 2√2) = 1 + √2: ${f.equals(f.sqrt(f.add(f.fromInt(3), f.mul(f.fromInt(2), f.sqrt(f.fromInt(2))!)))!, f.add(f.fromInt(1), f.sqrt(f.fromInt(2))!))}');
}
Output
√(3 + 2√2) = 1 + √2: true
sqrtmethod
AlgebraicNumber? sqrt(AlgebraicNumber a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  print('√5 ≈ ${f.toDouble(f.sqrt(f.fromInt(5))!)}, √(−1) = ${f.sqrt(f.fromInt(-1))}');
}
Output
√5 ≈ 2.23606797749979, √(−1) = null
signmethod
int sign(AlgebraicNumber a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  // √2 + √3 − √10 ≈ −0.016: a small negative number, signed exactly.
  final x = f.sub(f.add(f.sqrt(f.fromInt(2))!, f.sqrt(f.fromInt(3))!), f.sqrt(f.fromInt(10))!);
  print('sign(√2 + √3 − √10) = ${f.sign(x)}');
}
Output
sign(√2 + √3 − √10) = -1
toDoublemethod
double toDouble(AlgebraicNumber a)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const f = OrderedAlgebraic();
  print('√7 ≈ ${f.toDouble(f.sqrt(f.fromInt(7))!)}');
}
Output
√7 ≈ 2.6457513110645907
toStringmethod
String toString()
class

Quad

final class Quad<T>

The element a + b\sqrt{d} of a QuadraticExtension; d belongs to the field, not the element, so print it with the field's format (1 + 3√2). Its own toString shows a literal d: (1/2 + 1/2√d).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // a + b√d, here in ℚ(√2).
  final q2 = RealQuadraticField.of(2);
  final x = q2.make(rat(1), rat(1));
  print('x = ${q2.formatQuad(x)}, x² = ${q2.formatQuad(q2.mul(x, x))}');
}
Output
x = 1 + 1√2, x² = 3 + 2√2

Constructors

Quadconstructor
const Quad(this.a, this.b)

The element a + b√d.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q3 = RealQuadraticField.of(3);
  final x = Quad(rat(2), rat(1));
  print('${q3.formatQuad(x)}, norm ${q3.norm(x)}  (a unit: 2² − 3·1² = 1)');
}
Output
2 + 1√3, norm 1  (a unit: 2² − 3·1² = 1)

Properties

afield
final T a

The rational part a and the coefficient b of \sqrt{d}, both in the base field.

bfield
final T b

The rational part a and the coefficient b of \sqrt{d}, both in the base field.

hashCodegetter
int get hashCode

Methods

toStringmethod
String toString()

Operators

operator ==operator
bool operator ==(Object other)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('(1 + √2)(1 − √2) == −1: ${q2.mul(q2.make(rat(1), rat(1)), q2.make(rat(1), rat(-1))) == q2.of(rat(-1))}');
}
Output
(1 + √2)(1 − √2) == −1: true
class QuadraticExtension<T> implements ScalarField<Quad<T>>

The quadratic extension F(\sqrt{d}) of the field base, where d is not a square in base: \mathbb{Q}(\sqrt{2}), \mathbb{Q}(\sqrt{5}) (golden ratio), \mathbb{Q}(\sqrt{-1}) (Gaussian rationals), F_{p^{2}} = \mathbb{Z}/p(\sqrt{n}) with n from nonSquareMod.

Elements are Quads a + b√d with a, b in base; arithmetic is exact, using \sqrt{d} \cdot \sqrt{d} = d. Over \mathbb{Q} with d > 0, use RealQuadraticField to also get the order.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // F(√d) over any base field: the Gaussian rationals ℚ(√−1).
  final g = QuadraticExtension(Q, rat(-1));
  final i = g.root;
  print('i² = ${g.formatQuad(g.mul(i, i))}, (1 + i)⁻¹ = ${g.formatQuad(g.inv(g.make(rat(1), rat(1))))}');
}
Output
i² = -1, (1 + i)⁻¹ = 1/2 + -1/2√-1

Constructors

QuadraticExtension(this.base, this.d)

F(√d) over base. Throws ArgumentError when d already has a square root in base (then F(\sqrt{d}) would be F itself, not a field extension).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The field with 49 elements: ℤ/7 with √3 adjoined (3 is not a square mod 7).
  final f7 = PrimeField(7);
  final f49 = QuadraticExtension(f7, nonSquareMod(f7));
  final x = f49.make(2, 5);
  print('x = ${f49.formatQuad(x)}, x⁻¹ = ${f49.formatQuad(f49.inv(x))}, x·x⁻¹ = ${f49.formatQuad(f49.mul(x, f49.inv(x)))}');
}
Output
x = 2 + 5√3, x⁻¹ = 5 + 5√3, x·x⁻¹ = 1

Properties

basefield
final ScalarField<T> base

The field F that is extended.

dfield
final T d

The non-square d whose root is adjoined.

rootgetter
Quad<T> get root

The generator \sqrt{d}.

zerogetter
Quad<T> get zero
onegetter
Quad<T> get one
int get characteristic

Methods

ofmethod
Quad<T> of(T x)

The base-field element x as the element x + 0\sqrt{d}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('3/4 in ℚ(√2): ${q2.formatQuad(q2.of(rat(3, 4)))}');
}
Output
3/4 in ℚ(√2): 3/4
makemethod
Quad<T> make(T x, T y)

The element x + y√d.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q5 = RealQuadraticField.of(5);
  final phi = q5.make(rat(1, 2), rat(1, 2));
  print('φ = ${q5.formatQuad(phi)}, φ² − φ − 1 = ${q5.formatQuad(q5.sub(q5.sub(q5.mul(phi, phi), phi), q5.one))}');
}
Output
φ = 1/2 + 1/2√5, φ² − φ − 1 = 0
conjugatemethod
Quad<T> conjugate(Quad<T> x)

The conjugate a - b\sqrt{d}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  final x = q2.make(rat(3), rat(2));
  print('conj(${q2.formatQuad(x)}) = ${q2.formatQuad(q2.conjugate(x))}, product ${q2.formatQuad(q2.mul(x, q2.conjugate(x)))}');
}
Output
conj(3 + 2√2) = 3 + -2√2, product 1
normmethod
T norm(Quad<T> x)

The norm a^{2} - d b^{2} of x = a + b\sqrt{d}, the product x \cdot \bar{x} with its conjugate; it lies in the base field and is zero only for x = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('N(3 + 2√2) = ${q2.norm(q2.make(rat(3), rat(2)))}, N(1 + √2) = ${q2.norm(q2.make(rat(1), rat(1)))}');
}
Output
N(3 + 2√2) = 1, N(1 + √2) = -1
addmethod
Quad<T> add(Quad<T> x, Quad<T> y)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('${q2.formatQuad(q2.add(q2.make(rat(1), rat(1)), q2.make(rat(1, 2), rat(-3))))}');
}
Output
3/2 + -2√2
submethod
Quad<T> sub(Quad<T> x, Quad<T> y)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('${q2.formatQuad(q2.sub(q2.make(rat(1), rat(1)), q2.make(rat(1), rat(1))))}');
}
Output
0
mulmethod
Quad<T> mul(Quad<T> x, Quad<T> y)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // (a + b√d)(c + e√d) = (ac + d·be) + (ae + bc)√d.
  final q2 = RealQuadraticField.of(2);
  var x = q2.one;
  for (var n = 1; n <= 5; n++) {
    x = q2.mul(x, q2.make(rat(1), rat(1)));
    print('(1 + √2)^$n = ${q2.formatQuad(x)}');
  }
}
Output
(1 + √2)^1 = 1 + 1√2
(1 + √2)^2 = 3 + 2√2
(1 + √2)^3 = 7 + 5√2
(1 + √2)^4 = 17 + 12√2
(1 + √2)^5 = 41 + 29√2
negmethod
Quad<T> neg(Quad<T> x)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('${q2.formatQuad(q2.neg(q2.make(rat(1), rat(-1))))}');
}
Output
-1 + 1√2
invmethod
Quad<T> inv(Quad<T> x)

The inverse \frac{1}{x} = \bar{x} / N(x): the conjugate divided by the norm. Throws UnsupportedError for x = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('1/(1 + √2) = ${q2.formatQuad(q2.inv(q2.make(rat(1), rat(1))))}');
}
Output
1/(1 + √2) = -1 + 1√2
isZeromethod
bool isZero(Quad<T> x)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  final x = q2.make(rat(1), rat(1));
  print('x·x⁻¹ − 1 is zero: ${q2.isZero(q2.sub(q2.mul(x, q2.inv(x)), q2.one))}');
}
Output
x·x⁻¹ − 1 is zero: true
equalsmethod
bool equals(Quad<T> a, Quad<T> b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('(1 + √2)² = 3 + 2√2: ${q2.equals(q2.mul(q2.make(rat(1), rat(1)), q2.make(rat(1), rat(1))), q2.make(rat(3), rat(2)))}');
}
Output
(1 + √2)² = 3 + 2√2: true
fromIntmethod
Quad<T> fromInt(int n)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('${q2.formatQuad(q2.fromInt(7))}');
}
Output
7
Quad<T> fromRational(Rational r)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('${q2.formatQuad(q2.fromRational(rat(2, 3)))}');
}
Output
2/3
divmethod
Quad<T> div(Quad<T> a, Quad<T> b)
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('(3 + 2√2)/(1 + √2) = ${q2.formatQuad(q2.div(q2.make(rat(3), rat(2)), q2.make(rat(1), rat(1))))}');
}
Output
(3 + 2√2)/(1 + √2) = 1 + 1√2
sqrtmethod
Quad<T>? sqrt(Quad<T> x)

A square root u + v\sqrt{d} of x = a + b\sqrt{d} inside this field, or null when x is not a square here.

Solves u^{2} + d v^{2} = a and 2uv = b, so u^{2} = \frac{a \pm \sqrt{a^{2} - d b^{2}}}{2}. For b = 0 the root is either a base-field root of a or a multiple of \sqrt{d} (\sqrt{2} in \mathbb{Q}(\sqrt{2}) is 0 + 1√2). Example in \mathbb{Q}(\sqrt{2}): \sqrt{3 + 2\sqrt{2}} = 1 + \sqrt{2}, and \sqrt{3} is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q2 = RealQuadraticField.of(2);
  print('√(3 + 2√2) = ${q2.sqrt(q2.make(rat(3), rat(2))).let(q2)}');
  print('√(1 + √2) = ${q2.sqrt(q2.make(rat(1), rat(1)))}  (not in ℚ(√2))');
}

extension on Quad<Rational>? {
  String let(RealQuadraticField f) => this == null ? 'none' : f.formatQuad(this!);
}
Output
√(3 + 2√2) = 1 + 1√2
√(1 + √2) = null  (not in ℚ(√2))
String formatQuad(Quad<T> a)

A readable form of a: 1 + 3√2, 3√2 when the rational part is zero, and just the base element when the \sqrt{d} part is zero. FieldOps.format uses this for elements of an extension.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q5 = RealQuadraticField.of(5);
  for (final x in [q5.make(rat(1, 2), rat(1, 2)), q5.of(rat(3)), q5.root, q5.make(rat(-1), rat(-2))]) print(q5.formatQuad(x));
}
Output
1/2 + 1/2√5
3
1√5
-1 + -2√5
toStringmethod
String toString()
final class RealQuadraticField extends QuadraticExtension<Rational> implements OrderedField<Quad<Rational>>

\mathbb{Q}(\sqrt{d}) for a rational d > 0 that is not a square, with the order it has as a subfield of \mathbb{R} (\sqrt{d} taken positive): \operatorname{sign}(a + b\sqrt{d}) is decided exactly by comparing a^{2} with d b^{2}, with no rounding.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // ℚ(√d) with d > 0 is ordered: signs are decided exactly by comparing a² with d·b².
  final q3 = RealQuadraticField.of(3);
  final x = q3.make(rat(-1351), rat(780)); // 780√3 − 1351 ≈ −0.00037
  print('sign(780√3 − 1351) = ${q3.sign(x)}, ≈ ${q3.toDouble(x)}');
}
Output
sign(780√3 − 1351) = -1, ≈ -0.00037009627571104865

Constructors

RealQuadraticField(Rational d)

\mathbb{Q}(√d). Throws ArgumentError when d is a perfect square in \mathbb{Q} (such as 4 or \frac{9}{4}) or when d \le 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final f = RealQuadraticField(rat(1, 2));
  print('ℚ(√(1/2)): root² = ${f.formatQuad(f.mul(f.root, f.root))}');
}
Output
ℚ(√(1/2)): root² = 1/2
factory RealQuadraticField.of(int d)

\mathbb{Q}(√d) for an integer d, such as RealQuadraticField.of(2) for \mathbb{Q}(\sqrt{2}); the same checks as the main constructor.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q7 = RealQuadraticField.of(7);
  print('${q7}, √7 ≈ ${q7.toDouble(q7.root)}');
}
Output
ℚ(√7), √7 ≈ 2.6457513110645907

Methods

signmethod
int sign(Quad<Rational> x)

The exact sign of a + b\sqrt{d}: when a and b have opposite signs, the larger of a^{2} and d b^{2} decides.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // 99 − 70√2 ≈ 0.00505 > 0.
  final q2 = RealQuadraticField.of(2);
  print('sign(99 − 70√2) = ${q2.sign(q2.make(rat(99), rat(-70)))}');
}
Output
sign(99 − 70√2) = 1
toDoublemethod
double toDouble(Quad<Rational> x)

a + b\sqrt{d} as a double. When a and b\sqrt{d} have opposite signs it uses \frac{a^{2} - d b^{2}}{a - b\sqrt{d}}, which avoids the cancellation of subtracting two nearly equal doubles, so 1 - \sqrt{2} keeps full relative accuracy.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // toDouble divides the norm by the conjugate, so a tiny value like 99 − 70√2 keeps its digits.
  final q2 = RealQuadraticField.of(2);
  print('99 − 70√2 ≈ ${q2.toDouble(q2.make(rat(99), rat(-70)))}');
  print('naive doubles: ${99 - 70 * 1.4142135623730951}');
}
Output
99 − 70√2 ≈ 0.005050633883346584
naive doubles: 0.005050633883342925
class

IVec3

final class IVec3

An integer 3-vector (a lattice point or a lattice direction).

All arithmetic is exact integer arithmetic; keep coordinates below 2^{31} in magnitude so that dot products and quadrances stay inside 64-bit integers (this is not checked).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = IVec3(1, 2, 2), b = IVec3(2, -2, 1);
  print('a·b = ${a.dot(b)}, a × b = ${a.cross(b)}, Q(a) = ${a.quadrance}');
}
Output
a·b = 0, a × b = (6, 3, -6), Q(a) = 9

Constructors

IVec3constructor
const IVec3(this.x, this.y, this.z)

The vector (x, y, z).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${const IVec3(3, 4, 12)}, quadrance ${const IVec3(3, 4, 12).quadrance}');
}
Output
(3, 4, 12), quadrance 169

Properties

xfield
final int x

The coordinates.

yfield
final int y

The coordinates.

zfield
final int z

The coordinates.

quadrancegetter
int get quadrance

x^{2} + y^{2} + z^{2}, exact (|coordinates| < 2^{31} keeps it below 2^{63}).

hashCodegetter
int get hashCode

Methods

dotmethod
int dot(IVec3 o)

The dot product x \cdot x' + y \cdot y' + z \cdot z' with o.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, 1, 0).dot(IVec3(1, -1, 5))}');
}
Output
0
crossmethod
IVec3 cross(IVec3 o)

The cross product with o: perpendicular to both, with quadrance Q(u) \cdot Q(v) \cdot s, s the spread between them.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('x × y = ${IVec3(1, 0, 0).cross(IVec3(0, 1, 0))}');
}
Output
x × y = (0, 0, 1)
int quadranceTo(IVec3 o)

The quadrance between this point and o, exact.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, 1, 1).quadranceTo(IVec3(-1, -1, -1))}');
}
Output
12
spreadTomethod
Rational spreadTo(IVec3 o)

The exact spread to o: 1 - \frac{(u \cdot v)^{2}}{Q(u)Q(v)} as a Rational; 0 for parallel vectors, 1 for perpendicular ones. Throws ArgumentError (zero denominator) if either vector is zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Spreads between FCC strut directions: 1/4, 3/4 and 1 occur.
  final d = IVec3(1, 1, 0);
  for (final e in [IVec3(1, 0, 1), IVec3(0, 0, 2), IVec3(1, -1, 0)]) print('spread to $e: ${d.spreadTo(e)}');
}
Output
spread to (1, 0, 1): 3/4
spread to (0, 0, 2): 1
spread to (1, -1, 0): 1
toVecmethod
Vec<Rational> toVec()

The same vector as a 3-vector over Q, for use with the general field-based geometry.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, -2, 3).toVec()}');
}
Output
[1, -2, 3]
toStringmethod
String toString()

The vector as (x, y, z).

Operators

operator +operator
IVec3 operator +(IVec3 o)

The sum, coordinate by coordinate.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, 2, 3) + IVec3(1, 1, 1)}');
}
Output
(2, 3, 4)
operator -operator
IVec3 operator -(IVec3 o)

The difference, coordinate by coordinate.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, 2, 3) - IVec3(1, 1, 1)}');
}
Output
(0, 1, 2)
operator -operator
IVec3 operator -()

The opposite vector (-x, -y, -z).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${-IVec3(1, -2, 3)}');
}
Output
(-1, 2, -3)
operator *operator
IVec3 operator *(int k)

The vector scaled by the integer k.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, 2, 3) * 4}');
}
Output
(4, 8, 12)
operator ==operator
bool operator ==(Object other)

Equal when all three coordinates are equal.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${IVec3(1, 2, 3) + IVec3(1, 1, 1) == IVec3(2, 3, 4)}, ${IVec3(1, 0, 0) == IVec3(0, 1, 0)}');
}
Output
true, false
class

IMat3

final class IMat3

A 3 \times 3 integer matrix (a lattice symmetry), row-major.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A quarter turn about z as an integer matrix.
  final r = IMat3([0, -1, 0, 1, 0, 0, 0, 0, 1]);
  print('(1, 0, 0) ↦ ${r.apply(IVec3(1, 0, 0))}, r⁴ = I: ${r * r * r * r == IMat3.identity}');
}
Output
(1, 0, 0) ↦ (0, 1, 0), r⁴ = I: true

Constructors

IMat3constructor
const IMat3(this.m)

The matrix with the 9 entries m in row-major order (m[3i + j] is row i, column j). The length is not checked; a list shorter than 9 makes later operations throw RangeError.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = IMat3([1, 0, 0, 0, 0, -1, 0, 1, 0]);
  print('orthogonal ${m.isOrthogonal}, det ${m.determinant}');
}
Output
orthogonal true, det 1

Static

identityconstant
static const IMat3 identity = IMat3([1, 0, 0, 0, 1, 0, 0, 0, 1])

The identity matrix I.

Properties

mfield
final List<int> m

The 9 entries, row by row.

transposegetter
IMat3 get transpose

The transpose M^{T}.

int get determinant

The determinant \det M: +1 for a rotation in octahedralGroup, -1 for a reflection.

bool get isOrthogonal

Whether M is orthogonal, M^{T}M = I, so that it keeps every quadrance and spread. The integer orthogonal matrices are exactly the 48 signed permutation matrices of octahedralGroup.

hashCodegetter
int get hashCode

Methods

applymethod
IVec3 apply(IVec3 v)

The image M v of v, exactly.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final swap = IMat3([0, 1, 0, 1, 0, 0, 0, 0, 1]);
  print('${swap.apply(IVec3(1, 2, 3))}');
}
Output
(2, 1, 3)

Operators

operator *operator
IMat3 operator *(IMat3 o)

The matrix product M·o: applying the result means applying o first, then this matrix.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = IMat3([0, -1, 0, 1, 0, 0, 0, 0, 1]), b = IMat3([1, 0, 0, 0, 0, -1, 0, 1, 0]);
  print('ab == ba: ${a * b == b * a}');
}
Output
ab == ba: false
operator ==operator
bool operator ==(Object other)

Equal when all 9 entries are equal.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = IMat3([0, -1, 0, 1, 0, 0, 0, 0, 1]);
  print('r² == half turn: ${r * r == IMat3([-1, 0, 0, 0, -1, 0, 0, 0, 1])}');
}
Output
r² == half turn: true
enum CubicLattice

The cubic lattices and their nearest-neighbour shells, in integer coordinates.

Values

simplevalue
simple

\mathbb{Z}^{3}: 6 neighbours at quadrance 1.

bodyCentred

Points with all coordinates even or all odd: 8 neighbours (\pm1, \pm1, \pm1) at quadrance 3.

faceCentred

Points with even coordinate sum: 12 neighbours (permutations of (\pm1, \pm1, 0)) at quadrance 2. The octet truss is this lattice with its nearest-neighbour struts; its Voronoi cell is the rhombic dodecahedron.

Properties

int get neighbourQuadrance

The nearest-neighbour quadrance: 1, 3 or 2 for simple, body-centred and face-centred.

List<IVec3> get neighbours

The nearest-neighbour directions (the struts of the lattice truss): 6, 8 or 12 vectors, a new list each call.

Methods

containsmethod
bool contains(IVec3 p)

Whether the integer point p belongs to this lattice.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = IVec3(1, 1, 0);
  for (final l in CubicLattice.values) print('$l contains $p: ${l.contains(p)}');
}
Output
CubicLattice.simple contains (1, 1, 0): true
CubicLattice.bodyCentred contains (1, 1, 0): false
CubicLattice.faceCentred contains (1, 1, 0): true
abstract final class LatticePolyhedra

Polyhedra with integer vertices (the modules of lattice self-assembly). Each method returns a new list of vertices centred on the origin.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('cube ${LatticePolyhedra.cube().length}, octahedron ${LatticePolyhedra.octahedron().length}, cuboctahedron ${LatticePolyhedra.cuboctahedron().length}, rhombic dodecahedron ${LatticePolyhedra.rhombicDodecahedron().length}, truncated octahedron ${LatticePolyhedra.truncatedOctahedron().length} vertices');
}
Output
cube 8, octahedron 6, cuboctahedron 12, rhombic dodecahedron 14, truncated octahedron 24 vertices

Static

static List<IVec3> rhombicDodecahedron()

The rhombic dodecahedron (Voronoi cell of the FCC lattice, scaled by 2): 8 vertices (\pm1, \pm1, \pm1) and 6 vertices (\pm2, 0, 0) and permutations; its 12 faces have normals (\pm1, \pm1, 0), the FCC neighbours.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = LatticePolyhedra.rhombicDodecahedron();
  print('${v.length} vertices: ${v.map((p) => p.quadrance).toSet()} (quadrances 3 and 4 from the centre)');
}
Output
14 vertices: {3, 4} (quadrances 3 and 4 from the centre)
static List<IVec3> rhombicDodecahedronFaceNormals()

The 12 face normals of the rhombic dodecahedron (= FCC neighbour directions, octet truss struts).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final n = LatticePolyhedra.rhombicDodecahedronFaceNormals();
  print('${n.length} face normals, e.g. ${n.take(4).join(', ')}');
}
Output
12 face normals, e.g. (-1, -1, 0), (-1, 0, -1), (-1, 0, 1), (-1, 1, 0)
cuboctahedronstaticmethod
static List<IVec3> cuboctahedron()

The cuboctahedron (the FCC nearest-neighbour shell): its 12 vertices are the permutations of (\pm1, \pm1, 0).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = LatticePolyhedra.cuboctahedron();
  print('${v.length} vertices, all at quadrance ${v.map((p) => p.quadrance).toSet()}');
}
Output
12 vertices, all at quadrance {2}
static List<IVec3> truncatedOctahedron()

The truncated octahedron (Voronoi cell of the BCC lattice, scaled by 4): its 24 vertices are the permutations of (0, \pm1, \pm2).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = LatticePolyhedra.truncatedOctahedron();
  print('${v.length} vertices, quadrance ${v.map((p) => p.quadrance).toSet()}');
}
Output
24 vertices, quadrance {5}
cubestaticmethod
static List<IVec3> cube()

The cube: the 8 vertices (\pm1, \pm1, \pm1).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${LatticePolyhedra.cube()}');
}
Output
[(-1, -1, -1), (-1, -1, 1), (-1, 1, -1), (-1, 1, 1), (1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)]
octahedronstaticmethod
static List<IVec3> octahedron()

The octahedron: the 6 vertices (\pm1, 0, 0) and permutations.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${LatticePolyhedra.octahedron()}');
}
Output
[(-1, 0, 0), (0, -1, 0), (0, 0, -1), (0, 0, 1), (0, 1, 0), (1, 0, 0)]
tetrahedronstaticmethod
static List<IVec3> tetrahedron()

The regular tetrahedron inscribed in the cube: (1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final t = LatticePolyhedra.tetrahedron();
  print('$t, edge quadrances ${{for (var i = 0; i < 4; i++) for (var j = i + 1; j < 4; j++) t[i].quadranceTo(t[j])}}');
}
Output
[(1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1)], edge quadrances {8}
final class FixedPointFormat

Fixed point with fractionBits fractional bits: x is stored as the integer X = x \cdot 2^{k}. Quadrances of stored values are exact integers in units of 4^{-k}. For GPU int32 storage |X| < 2^{31}; for int32 quadrance arithmetic on the GPU, keep |\Delta X| < 2^{14} per coordinate (3 \cdot 2^{28} < 2^{31}); on the CPU, int64 quadrances are exact for

\Delta X< 2^{31}.
Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Coordinates stored as integers in units of 2^-8: quadrances stay exact integers.
  const fmt = FixedPointFormat(8);
  print('stored 384 means ${fmt.decode(384)}; 3/16 is stored as ${fmt.encodeExact(rat(3, 16))}');
}
Output
stored 384 means 3/2; 3/16 is stored as 48

Constructors

FixedPointFormatconstructor
const FixedPointFormat(this.fractionBits)

The format with k = fractionBits fractional bits. Use 0 \le k \le 62; the range is not checked.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const fmt = FixedPointFormat(4);
  print('scale ${fmt.scale}, one unit = ${fmt.decode(1)}');
}
Output
scale 16, one unit = 1/16

Static

static const int float32ExactLimit = 1 << 24

2^{24}, the bound for exact float32 conversion: every stored integer of magnitude at most 2^{24} converts to float32 with no error.

Properties

final int fractionBits

The number k of fractional bits.

scalegetter
int get scale

The scale 2^{k}: the stored integer for the value 1.

Methods

decodemethod
Rational decode(int stored)

The exact rational X / 2^{k} that the stored integer stored means.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${const FixedPointFormat(10).decode(1536)}');
}
Output
3/2
int encodeExact(Rational r)

The stored integer r \cdot 2^{k} for the rational r. Throws ArgumentError unless r is a multiple of 2^{-k}: there is no silent rounding. The magnitude is not checked: a result beyond the 64-bit integer range comes back clamped.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const fmt = FixedPointFormat(4);
  print('5/8 → ${fmt.encodeExact(rat(5, 8))}');
  try {
    fmt.encodeExact(rat(1, 3));
  } catch (e) {
    print('1/3 → refused (no silent rounding)');
  }
}
Output
5/8 → 10
1/3 → refused (no silent rounding)
quadrancemethod
Rational quadrance(IVec3 a, IVec3 b)

The exact quadrance between two stored points a and b, as a rational in real units (the stored quadrance divided by 4^{k}).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  const fmt = FixedPointFormat(2);
  print('${fmt.quadrance(IVec3(0, 0, 0), IVec3(1, 2, 2))}  (the points (0,0,0) and (1/4, 1/2, 1/2))');
}
Output
9/16  (the points (0,0,0) and (1/4, 1/2, 1/2))
final class ExactLatticeState

The exact state of a lattice structure: integer node positions (fixed point) and struts. Only integers go in.

Nodes and struts are numbered from 0 in the order they are added. Index arguments are not range checked except in addStrut; an index past the end throws RangeError from the underlying list.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Exact integer state for a lattice structure; floats only ever in a one-way render snapshot.
  final s = ExactLatticeState(const FixedPointFormat(0));
  final a = s.addNode(IVec3(0, 0, 0)), b = s.addNode(IVec3(1, 1, 0));
  s.addStrut(a, b);
  print('strut quadrance ${s.strutQuadrance(0)}');
}
Output
strut quadrance 2

Constructors

ExactLatticeState(this.format)

An empty state whose stored coordinates use format.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(3));
  s.addNode(IVec3(8, 0, 0));
  print('node 0 = ${s.node(0)} stored, means ${s.format.decode(s.node(0).x)}');
}
Output
node 0 = (8, 0, 0) stored, means 1

Properties

formatfield
final FixedPointFormat format

How stored integers map to real coordinates.

nodeCountgetter
int get nodeCount

The number of nodes.

int get strutCount

The number of struts.

int get fingerprint

A 64-bit FNV-1a fingerprint of every coordinate and strut: equal fingerprints before and after rendering prove no float wrote back.

Methods

addNodemethod
int addNode(IVec3 stored)

Adds a node at integer (stored) coordinates and returns its index.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  print('indices ${s.addNode(IVec3(0, 0, 0))}, ${s.addNode(IVec3(1, 0, 1))}');
}
Output
indices 0, 1
addStrutmethod
void addStrut(int a, int b)

Adds a strut between nodes a and b. Throws RangeError unless both are existing node indices. Duplicate struts and a strut from a node to itself are not rejected.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(0, 0, 0));
  s.addNode(IVec3(1, 0, 1));
  s.addStrut(0, 1);
  print('strut ${s.strut(0)}, quadrance ${s.strutQuadrance(0)}');
}
Output
strut (0, 1), quadrance 2
moveNodemethod
void moveNode(int i, IVec3 by)

Moves node i by the integer offset by (stored units).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(0, 0, 0));
  s.addNode(IVec3(1, 1, 0));
  s.addStrut(0, 1);
  s.moveNode(1, IVec3(0, 0, 1));
  print('node 1 now ${s.node(1)}, strut quadrance ${s.strutQuadrance(0)}');
}
Output
node 1 now (1, 1, 1), strut quadrance 3
transformmethod
void transform(IMat3 g)

Applies a lattice symmetry g about the origin to every node, exactly, in place.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(1, 2, 3));
  s.transform(IMat3([0, -1, 0, 1, 0, 0, 0, 0, 1]));
  print('after a quarter turn: ${s.node(0)}');
}
Output
after a quarter turn: (-2, 1, 3)
nodemethod
IVec3 node(int i)

The stored coordinates of node i.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(5, -1, 2));
  print('${s.node(0)}');
}
Output
(5, -1, 2)
strutmethod
(int, int) strut(int k)

The two node indices joined by strut k.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  for (final p in LatticePolyhedra.tetrahedron()) s.addNode(p);
  s.addStrut(0, 1);
  s.addStrut(2, 3);
  print('struts ${s.strut(0)}, ${s.strut(1)}');
}
Output
struts (0, 1), (2, 3)
int strutQuadrance(int k)

The exact integer quadrance (stored units) of strut k; divide by 4^{k}, or use FixedPointFormat.quadrance, for real units.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  for (final p in LatticePolyhedra.tetrahedron()) s.addNode(p);
  for (var i = 0; i < 4; i++) for (var j = i + 1; j < 4; j++) s.addStrut(i, j);
  print('all six struts: ${[for (var k = 0; k < 6; k++) s.strutQuadrance(k)]}');
}
Output
all six struts: [8, 8, 8, 8, 8, 8]
Int32List toInt32Buffer()

The GPU buffer of node coordinates, x, y, z per node (a copy; the GPU never writes back through it).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(1, 2, 3));
  s.addNode(IVec3(-4, 5, 6));
  print('${s.toInt32Buffer()}');
}
Output
[1, 2, 3, -4, 5, 6]
Uint32List toIndexBuffer()

The strut index buffer: two node indices per strut (a copy).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  for (final p in LatticePolyhedra.tetrahedron()) s.addNode(p);
  s.addStrut(0, 1);
  s.addStrut(1, 2);
  print('${s.toIndexBuffer()}');
}
Output
[0, 1, 1, 2]
RenderSnapshot renderSnapshot()

A one-way float view for drawing: a new RenderSnapshot that shares nothing with this state.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(2));
  s.addNode(IVec3(1, 2, 3));
  final snap = s.renderSnapshot();
  print('float32 positions ${snap.positions}');
}
Output
float32 positions [0.25, 0.5, 0.75]
final class RenderSnapshot

A float32 copy of an exact state for the renderer. It holds no reference to the state and has no way back. Create one with ExactLatticeState.renderSnapshot.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(1));
  s.addNode(IVec3(1, 0, 0));
  s.addNode(IVec3(0, 3, 0));
  s.addStrut(0, 1);
  final r = s.renderSnapshot();
  print('positions ${r.positions}, indices ${r.indices}');
}
Output
positions [0.5, 0.0, 0.0, 0.0, 1.5, 0.0], indices [0, 1]

Properties

final Float32List positions

Node positions in world units (x, y, z per node), float32.

indicesfield
final Uint32List indices

The strut index buffer: two node indices per strut, as in ExactLatticeState.toIndexBuffer.

final double maxError

The largest |\text{float32} - \text{exact}| over all coordinates: 0 when every stored coordinate is below 2^{24} in magnitude.

final int sourceFingerprint

The fingerprint of the state this was taken from.

abstract final class FeedbackGuard

Runs a render pass and proves it did not touch the exact state.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(1, 1, 1));
  FeedbackGuard.render(s, (snap) => print('drawing ${snap.positions.length ~/ 3} node(s)'));
  print('exact state untouched');
}
Output
drawing 1 node(s)
exact state untouched

Static

renderstaticmethod
static void render(ExactLatticeState state, void Function(RenderSnapshot snapshot) render)

Calls render with a fresh snapshot of state and throws StateError if the exact state's fingerprint changed meanwhile.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final s = ExactLatticeState(const FixedPointFormat(0));
  s.addNode(IVec3(1, 1, 1));
  try {
    FeedbackGuard.render(s, (snap) => s.moveNode(0, IVec3(1, 0, 0))); // a renderer that writes back
  } on StateError {
    print('caught: the render pass changed the exact state');
  }
}
Output
caught: the render pass changed the exact state
abstract final class ProjectiveLaws

The projective (universal hyperbolic / elliptic) laws (Wildberger, "Universal hyperbolic geometry I: trigonometry", Geometriae Dedicata 163 (2013) 215–274). Projective quadrances q and spreads S of a triangle obey: the triple quad formula is the triple spread formula; Pythagoras is q_{3} = q_{1} + q_{2} - q_{1}q_{2}; the spread law is the planar one; the cross law is (q_{1}q_{2}S_{3} - q_{1} - q_{2} - q_{3} + 2)^{2} = 4(1 - q_{1})(1 - q_{2})(1 - q_{3}); and dually for spreads.

All members are static checks over a ScalarField f; q_{1}, q_{2}, q_{3} are the quadrances of the sides opposite the vertices a_{1}, a_{2}, a_{3} and S_{i} the spread at a_{i}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The laws of universal hyperbolic and elliptic trigonometry, as checks on rational numbers.
  final q1 = rat(1, 2), q2 = rat(1, 3);
  final q3 = q1 + q2 - q1 * q2;
  print('Pythagoras q3 = q1 + q2 − q1q2 = $q3: ${ProjectiveLaws.pythagorasHolds(Q, q1, q2, q3)}');
  print('cross law with S3 = 1: ${ProjectiveLaws.crossLawHolds(Q, q1, q2, q3, rat(1))}');
}
Output
Pythagoras q3 = q1 + q2 − q1q2 = 2/3: true
cross law with S3 = 1: true

Static

tripleQuadHoldsstaticmethod
static bool tripleQuadHolds<T>(ScalarField<T> f, T q1, T q2, T q3)

Whether the projective triple quad formula holds for q_{1}, q_{2}, q_{3}: it has the same shape as the planar triple spread formula, (q_{1} + q_{2} + q_{3})^{2} = 2(q_{1}^{2} + q_{2}^{2} + q_{3}^{2}) + 4q_{1}q_{2}q_{3}, and holds for the quadrances of three collinear points.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Projective quadrances of three collinear points obey the triple quad formula with the extra 4q₁q₂q₃ term.
  print('(1/4, 1/4, 3/4): ${ProjectiveLaws.tripleQuadHolds(Q, rat(1, 4), rat(1, 4), rat(3, 4))}');
  print('(1, 4, 9) (collinear in the plane, not projectively): ${ProjectiveLaws.tripleQuadHolds(Q, rat(1), rat(4), rat(9))}');
}
Output
(1/4, 1/4, 3/4): true
(1, 4, 9) (collinear in the plane, not projectively): false
pythagorasHoldsstaticmethod
static bool pythagorasHolds<T>(ScalarField<T> f, T q1, T q2, T q3)

Whether projective Pythagoras holds: q_{3} = q_{1} + q_{2} - q_{1}q_{2}, the relation for a right spread S_{3} = 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  print('(1/2, 1/2, 3/4): ${ProjectiveLaws.pythagorasHolds(Q, rat(1, 2), rat(1, 2), rat(3, 4))}');
  print('(1/2, 1/2, 1): ${ProjectiveLaws.pythagorasHolds(Q, rat(1, 2), rat(1, 2), rat(1))}  (the plane answer is wrong here)');
}
Output
(1/2, 1/2, 3/4): true
(1/2, 1/2, 1): false  (the plane answer is wrong here)
crossLawstaticmethod
static T crossLaw<T>(ScalarField<T> f, T q1, T q2, T q3, T s3)

The projective cross law residual (q_{1}q_{2}S_{3} - q_{1} - q_{2} - q_{3} + 2)^{2} - 4(1 - q_{1})(1 - q_{2})(1 - q_{3}); zero when the law holds.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final q1 = rat(1, 2), q2 = rat(1, 3), q3 = rat(2, 3);
  print('residual at S3 = 1: ${ProjectiveLaws.crossLaw(Q, q1, q2, q3, rat(1))}');
  print('residual at S3 = 1/2: ${ProjectiveLaws.crossLaw(Q, q1, q2, q3, rat(1, 2))}');
}
Output
residual at S3 = 1: 0
residual at S3 = 1/2: -5/48
crossLawHoldsstaticmethod
static bool crossLawHolds<T>(ScalarField<T> f, T q1, T q2, T q3, T s3)

Whether the projective cross law holds: crossLaw is zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${ProjectiveLaws.crossLawHolds(Q, rat(1, 2), rat(1, 3), rat(2, 3), rat(1))}');
  print('${ProjectiveLaws.crossLawHolds(Q, rat(1, 2), rat(1, 3), rat(2, 3), rat(1, 2))}');
}
Output
true
false
crossDualLawHoldsstaticmethod
static bool crossDualLawHolds<T>(ScalarField<T> f, T s1, T s2, T s3, T q3)

Whether the dual cross law (S_{1}S_{2}q_{3} - S_{1} - S_{2} - S_{3} + 2)^{2} = 4(1 - S_{1})(1 - S_{2})(1 - S_{3}) holds: the cross law with the roles of quadrances and spreads swapped.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The dual law swaps spreads and quadrances.
  print('${ProjectiveLaws.crossDualLawHolds(Q, rat(1, 2), rat(1, 3), rat(2, 3), rat(1))}');
}
Output
true
final class Triangle<T>

A triangle in a metric (any SymmetricForm: blue, red, green, Lorentzian, 3-D, …). Following Wildberger, Q_{i} is the quadrance of the side opposite A_{i} and s_{i} the spread at A_{i}. measures goes straight into RtPlane's checks and solvers.

The six measures are computed once, on first use. A spread is undefined when a side through its vertex is null (quadrance zero, which includes two equal vertices); reading it then throws StateError. Check isNondegenerate first when that can happen.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  final t = Triangle(blue, qv([0, 0]), qv([4, 0]), qv([0, 3]));
  print('quadrances Q1 = ${t.q1}, Q2 = ${t.q2}, Q3 = ${t.q3}');
  print('spreads    s1 = ${t.s1}, s2 = ${t.s2}, s3 = ${t.s3}');
  print('quadrea ${t.quadrea} (16 × area², area 6)');
  print('every law holds: ${t.satisfiesAllLaws}');
}
Output
quadrances Q1 = 25, Q2 = 9, Q3 = 16
spreads    s1 = 1, s2 = 9/25, s3 = 16/25
quadrea 576 (16 × area², area 6)
every law holds: true

Constructors

Triangleconstructor
Triangle(this.form, this.a1, this.a2, this.a3)

The triangle with vertices a1, a2, a3, measured in form. The vertices must have the dimension of form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final t = Triangle(SymmetricForm.blue(Q), qv([0, 0]), qv([5, 0]), qv([2, 4]));
  print('Q = ${t.q1}, ${t.q2}, ${t.q3}; s = ${t.s1}, ${t.s2}, ${t.s3}');
  print('quadrea ${t.quadrea}, all laws ${t.satisfiesAllLaws}');
}
Output
Q = 25, 20, 25; s = 4/5, 16/25, 4/5
quadrea 1600, all laws true

Properties

formfield
final SymmetricForm<T> form

The metric the triangle is measured in.

a1field
final Vec<T> a1

The vertices A_{1}, A_{2}, A_{3}.

a2field
final Vec<T> a2

The vertices A_{1}, A_{2}, A_{3}.

a3field
final Vec<T> a3

The vertices A_{1}, A_{2}, A_{3}.

fgetter
ScalarField<T> get f

The field of form.

planegetter
RtPlane<T> get plane

The riptide_algebra RtPlane over f, whose laws and solvers take measures.

q1field
late final T q1

The quadrance Q_{1} = Q(A_{2}A_{3}) of the side opposite A_{1}.

q2field
late final T q2

The quadrance Q_{2} = Q(A_{1}A_{3}) of the side opposite A_{2}.

q3field
late final T q3

The quadrance Q_{3} = Q(A_{1}A_{2}) of the side opposite A_{3}.

s1field
late final T s1

The spread s_{1} at A_{1}, between the sides A_{1}A_{2} and A_{1}A_{3}. Throws StateError when either side is null.

s2field
late final T s2

The spread s_{2} at A_{2}, between the sides A_{2}A_{1} and A_{2}A_{3}. Throws StateError when either side is null.

s3field
late final T s3

The spread s_{3} at A_{3}, between the sides A_{3}A_{1} and A_{3}A_{2}. Throws StateError when either side is null.

measuresgetter
RtMeasures<T> get measures

The six measures (Q_{1}, Q_{2}, Q_{3}, s_{1}, s_{2}, s_{3}), for RtPlane.satisfiesLaws, RtPlane.solveTriangle and the rest of riptide_algebra. Throws StateError when a side is null, since its spreads are undefined.

quadreagetter
T get quadrea

The quadrea \mathcal{A} = A(Q_{1}, Q_{2}, Q_{3}), Archimedes' function of the three quadrances (16 \cdot \mathrm{area}^{2} for blue). Needs no spreads, so it never throws.

bool get isCollinear

Whether the vertices are collinear: the quadrea is zero (the triple quad formula).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  final flat = Triangle(blue, qv([0, 0]), qv([1, 2]), qv([3, 6]));
  final real = Triangle(blue, qv([0, 0]), qv([1, 2]), qv([3, 5]));
  print('(0,0) (1,2) (3,6): collinear ${flat.isCollinear}, quadrea ${flat.quadrea}');
  print('(0,0) (1,2) (3,5): collinear ${real.isCollinear}, quadrea ${real.quadrea}');
}
Output
(0,0) (1,2) (3,6): collinear true, quadrea 0
(0,0) (1,2) (3,5): collinear false, quadrea 4
bool get isNondegenerate

Whether every side is non-null and the vertices are not collinear, so every spread is defined.

bool get satisfiesAllLaws

Whether the measures satisfy the five laws through RtPlane.satisfiesLaws (spread law, triple spread, cross law at every vertex) and the quadrea identity \mathcal{A} = 4Q_{1}Q_{2}s_{3}. Throws StateError when a side is null, as measures does.

class

Vec

final class Vec<T>

A point or vector with coordinates in a ScalarField.

The same type serves for affine points, for the vectors between them and for homogeneous coordinates of projective points (homogenize, dehomogenize, isProportionalTo). Vectors are immutable; arithmetic returns new vectors. Binary operations expect both vectors to have the same dimension and do not check it.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final a = qv([1, 0, 0]), b = qv([0, 1, 0]);
  print('a × b = ${a.cross(b)}');
  print('a · b = ${a.dot(b)}');
  print('quadrance of (1, 2, 2) = ${qv([1, 2, 2]).dot(qv([1, 2, 2]))}');
  print('proportional: ${qv([1, 2]).isProportionalTo(qv([3, 6]))}');
}
Output
a × b = [0, 0, 1]
a · b = 0
quadrance of (1, 2, 2) = 9
proportional: true

Constructors

Vecconstructor
Vec(this.field, List<T> coords)

The vector with coordinates coords over field. The list is copied, so later changes to coords do not affect the vector.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A vector over any field: here ℚ, then ℤ/7.
  final v = Vec(Q, [rat(1, 2), rat(-3), rat(2, 3)]);
  print('v = $v, dimension ${v.dim}');
  final w = Vec(PrimeField(7), [3, 5]);
  print('over ℤ/7: $w, 2w = ${w.scale(2)}');
}
Output
v = [1/2, -3, 2/3], dimension 3
over ℤ/7: [3, 5], 2w = [6, 3]
Vec.zerofactory
factory Vec.zero(ScalarField<T> field, int n)

The zero vector of dimension n.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final z = Vec.zero(Q, 3);
  print('zero of ℚ³: $z');
  print('v + 0 == v: ${qv([1, 2, 3]) + z == qv([1, 2, 3])}');
}
Output
zero of ℚ³: [0, 0, 0]
v + 0 == v: true
factory Vec.fromRtPoint(ScalarField<T> field, RtPoint<T> p)

The planar vector (p.x, p.y) of riptide_algebra's RtPoint p.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // From riptide_algebra's planar point type and back.
  final p = RtPoint<Rational>(rat(3, 4), rat(-1));
  final v = Vec.fromRtPoint(Q, p);
  print('vector $v, back to a point: ${v.toRtPoint()}');
}
Output
vector [3/4, -1], back to a point: [3/4, -1]
Vec.basisfactory
factory Vec.basis(ScalarField<T> field, int n, int i)

The standard basis vector e_{i} of dimension n: 1 in coordinate i (counting from 0), 0 elsewhere.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  for (var i = 0; i < 3; i++) print('e$i = ${Vec.basis(Q, 3, i)}');
  print('e0 × e1 = ${Vec.basis(Q, 3, 0).cross(Vec.basis(Q, 3, 1))}');
}
Output
e0 = [1, 0, 0]
e1 = [0, 1, 0]
e2 = [0, 0, 1]
e0 × e1 = [0, 0, 1]

Properties

fieldfield
final ScalarField<T> field

The field the coordinates live in.

cfield
final List<T> c

The coordinates, as an unmodifiable list.

dimgetter
int get dim

The number of coordinates.

xgetter
T get x

The first coordinate.

ygetter
T get y

The second coordinate. Throws RangeError for a 1-D vector.

zgetter
T get z

The third coordinate. Throws RangeError when dim < 3.

isZerogetter
bool get isZero

Whether every coordinate is zero.

hashCodegetter
int get hashCode

A hash of the coordinates.

Methods

scalemethod
Vec<T> scale(T k)

The scalar multiple k \cdot v.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = qv([2, -4, 6]);
  print('v = $v');
  print('v scaled by 1/2 = ${v.scale(rat(1, 2))}');
  print('v scaled by 0 = ${v.scale(rat(0))}');
}
Output
v = [2, -4, 6]
v scaled by 1/2 = [1, -2, 3]
v scaled by 0 = [0, 0, 0]
dotmethod
T dot(Vec<T> o)

The Euclidean (blue) dot product \sum x_{i}y_{i}. For any other metric use SymmetricForm.apply.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final u = qv([1, 2, 2]), v = qv([2, -1, 0]);
  print('u·u = ${u.dot(u)}  (the blue quadrance of u)');
  print('u·v = ${u.dot(v)}  (perpendicular)');
}
Output
u·u = 9  (the blue quadrance of u)
u·v = 0  (perpendicular)
crossmethod
Vec<T> cross(Vec<T> o)

The 3-D cross product u \times v. In homogeneous coordinates it is also the join of two projective points and the meet of two projective lines. Throws ArgumentError unless both vectors are 3-D.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final u = qv([1, 2, 3]), v = qv([4, 5, 6]);
  final w = u.cross(v);
  print('u × v = $w');
  print('perpendicular to both: ${w.dot(u)}, ${w.dot(v)}');
  // Projectively: the cross of two points [x, y, 1] is the line through them.
  print('line through (0,0) and (1,1): ${qv([0, 0, 1]).cross(qv([1, 1, 1]))}');
}
Output
u × v = [-3, 6, -3]
perpendicular to both: 0, 0
line through (0,0) and (1,1): [-1, 1, 0]
wedgemethod
T wedge(Vec<T> o)

The 2-D cross (wedge) x_{1}y_{2} - x_{2}y_{1}: the signed area of the parallelogram on the two vectors. Only the first two coordinates are used.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // x₁y₂ − x₂y₁: twice the signed area of the triangle 0, u, v.
  final u = qv([3, 1]), v = qv([1, 2]);
  print('u ∧ v = ${u.wedge(v)}, v ∧ u = ${v.wedge(u)}');
  print('parallel: ${u.wedge(u.scale(rat(5)))}');
}
Output
u ∧ v = 5, v ∧ u = -5
parallel: 0
toRtPointmethod
RtPoint<T> toRtPoint()

The same planar point as riptide_algebra's RtPoint. Throws StateError unless the vector is 2-D.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = qv(['1/3', 2]);
  final p = v.toRtPoint();
  print('as RtPoint: $p');
  print('quadrance to the origin with riptide_algebra: ${RtPlane<Rational>(Q).quadrance(p, RtPoint<Rational>(rat(0), rat(0)))}');
}
Output
as RtPoint: [1/3, 2]
quadrance to the origin with riptide_algebra: 37/9
bool isProportionalTo(Vec<T> o)

Whether this and o are proportional, that is, the same projective point: every 2 \times 2 minor x_{i}y_{j} - x_{j}y_{i} vanishes. The zero vector counts as proportional to every vector.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The same projective point: all 2 × 2 minors vanish.
  print('[1,2,3] ~ [2,4,6]: ${qv([1, 2, 3]).isProportionalTo(qv([2, 4, 6]))}');
  print('[1,2,3] ~ [-1/2,-1,-3/2]: ${qv([1, 2, 3]).isProportionalTo(qv(['-1/2', -1, '-3/2']))}');
  print('[1,2,3] ~ [1,2,4]: ${qv([1, 2, 3]).isProportionalTo(qv([1, 2, 4]))}');
}
Output
[1,2,3] ~ [2,4,6]: true
[1,2,3] ~ [-1/2,-1,-3/2]: true
[1,2,3] ~ [1,2,4]: false
Vec<T> dehomogenize()

The affine point (\frac{x}{w}, \frac{y}{w}, \ldots) of the homogeneous coordinates (x, y, \ldots, w), one dimension lower. Throws StateError when w = 0 (a point at infinity).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // [x, y, w] → (x/w, y/w).
  print('[2, 6, 4] → ${qv([2, 6, 4]).dehomogenize()}');
  print('[1, 1, 3] → ${qv([1, 1, 3]).dehomogenize()}');
}
Output
[2, 6, 4] → [1/2, 3/2]
[1, 1, 3] → [1/3, 1/3]
Vec<T> homogenize()

The homogeneous coordinates (x, y, \ldots, 1) of this affine point, one dimension higher. The inverse of dehomogenize.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = qv(['1/2', 3]);
  print('$p → ${p.homogenize()}');
  print('round trip: ${p.homogenize().dehomogenize()}');
}
Output
[1/2, 3] → [1/2, 3, 1]
round trip: [1/2, 3]
toStringmethod
String toString()

The coordinates in brackets, formatted by the field, e.g. [1/2, -3].

Operators

operator []operator
T operator [](int i)

The coordinate at index i (from 0). Throws RangeError when i is out of range.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = qv([7, '1/2', -3]);
  print('v[0] = ${v[0]}, v[1] = ${v[1]}, v[2] = ${v[2]}');
}
Output
v[0] = 7, v[1] = 1/2, v[2] = -3
operator +operator
Vec<T> operator +(Vec<T> o)

The sum, coordinate by coordinate. o must have the same dimension.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('[1, 2] + [1/2, -5] = ${qv([1, 2]) + qv(['1/2', -5])}');
}
Output
[1, 2] + [1/2, -5] = [3/2, -3]
operator -operator
Vec<T> operator -(Vec<T> o)

The difference this − o, coordinate by coordinate: the vector from the point o to this point.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // B − A: the vector from point A to point B.
  final a = qv([1, 1]), b = qv([4, 5]);
  print('B − A = ${b - a}, its quadrance ${(b - a).dot(b - a)}');
}
Output
B − A = [3, 4], its quadrance 25
operator -operator
Vec<T> operator -()

The negated vector -v.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final v = qv([1, '-2/3', 0]);
  print('−v = ${-v}, v + (−v) = ${v + -v}');
}
Output
−v = [-1, 2/3, 0], v + (−v) = [0, 0, 0]
operator ==operator
bool operator ==(Object other)

Exact equality: other is a Vec of the same type and dimension with equal coordinates in the field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Exact coordinate equality; for "the same projective point" use isProportionalTo.
  print('[1/2, 1] == [2/4, 1]: ${qv(['1/2', 1]) == qv(['2/4', 1])}');
  print('[1, 2] == [2, 4]: ${qv([1, 2]) == qv([2, 4])}, proportional: ${qv([1, 2]).isProportionalTo(qv([2, 4]))}');
}
Output
[1/2, 1] == [2/4, 1]: true
[1, 2] == [2, 4]: false, proportional: true
class

Mat

final class Mat<T>

A dense n \times m matrix over a ScalarField, stored row by row.

Matrices are immutable. Products, inverses, determinants and solutions are computed exactly by Gaussian elimination in the field, so a.inverse * a is exactly the identity. Shapes are not checked by the arithmetic operators; mismatched shapes give a RangeError or a wrong-sized result.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Mat(Q, [
    [rat(2), rat(1)],
    [rat(1), rat(3)],
  ]);
  print('m =\n$m');
  print('det = ${m.determinant}');
  print('inverse =\n${m.inverse}');
  print('m · m⁻¹ =\n${m * m.inverse!}');
  print('solve m x = (3, 5): ${m.solve(qv([3, 5]))}');
}
Output
m =
2 1
1 3
det = 5
inverse =
3/5 -1/5
-1/5 2/5
m · m⁻¹ =
1 0
0 1
solve m x = (3, 5): [4/5, 7/5]

Constructors

Matconstructor
Mat(this.field, List<List<T>> rows)

The matrix with rows rows over field. The rows are copied. m is taken from the first row; rows of other lengths are not rejected.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Mat(Q, [[rat(1), rat(2)], [rat(3), rat(4)]]);
  print(m);
  print('det = ${m.determinant}');
  print('inverse:\n${m.inverse}');
}
Output
1 2
3 4
det = -2
inverse:
-2 1
3/2 -1/2
factory Mat.identity(ScalarField<T> field, int n)

The n \times n identity matrix I.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final i = Mat.identity(Q, 3);
  print(i);
  final m = Mat(Q, [[rat(2), rat(1), rat(0)], [rat(0), rat(1), rat(0)], [rat(0), rat(0), rat(3)]]);
  print('I·M == M: ${i * m == m}');
}
Output
1 0 0
0 1 0
0 0 1
I·M == M: true
factory Mat.diagonal(ScalarField<T> field, List<T> d)

The square diagonal matrix \operatorname{diag}(d_{1}, \ldots, d_{k}) with the entries d on the diagonal.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The Minkowski metric diag(−1, 1, 1, 1).
  final eta = Mat.diagonal(Q, [rat(-1), rat(1), rat(1), rat(1)]);
  print(eta);
  print('det = ${eta.determinant}');
}
Output
-1 0 0 0
0 1 0 0
0 0 1 0
0 0 0 1
det = -1
factory Mat.columns(ScalarField<T> field, List<Vec<T>> cols)

The matrix whose columns are the vectors cols, all of the same dimension. Throws RangeError when cols is empty.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A matrix whose columns are the images of the basis vectors.
  final m = Mat.columns(Q, [qv([3, 4]), qv([-4, 3])]);
  print(m);
  print('M e0 = ${m.apply(qv([1, 0]))}');
}
Output
3 -4
4 3
M e0 = [3, 4]

Properties

fieldfield
final ScalarField<T> field

The field the entries live in.

rowsfield
final List<List<T>> rows

The entries, row by row, as unmodifiable lists.

nfield
final int n

The number of rows (n) and of columns (m).

mfield
final int m

The number of rows (n) and of columns (m).

transposegetter
Mat<T> get transpose

The transpose A^{T}, an m \times n matrix.

T get determinant

The determinant det A, exactly, by Gaussian elimination over the field. Throws StateError when the matrix is not square.

inversegetter
Mat<T> get inverse

The inverse A^{-1}, exactly, by Gauss–Jordan elimination. Throws UnsupportedError when the matrix is singular (det A = 0) and StateError when it is not square. To get null instead of an exception, use solve.

adjugategetter
Mat<T> get adjugate

The adjugate (classical adjoint) adj A, the transposed matrix of cofactors, so that \operatorname{adj}(A) \cdot A = \det(A) \cdot I. Unlike inverse it is defined for singular matrices too, and it uses no division. A 1 \times 1 matrix has adjugate [[1]]. Throws StateError when the matrix is not square.

hashCodegetter
int get hashCode

A hash of the entries.

Methods

atmethod
T at(int i, int j)

The entry in row i and column j (both from 0).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Mat(Q, [[rat(1), rat(2)], [rat(3), rat(4)]]);
  print('m(0,1) = ${m.at(0, 1)}, m(1,0) = ${m.at(1, 0)}');
}
Output
m(0,1) = 2, m(1,0) = 3
scalemethod
Mat<T> scale(T k)

The scalar multiple k \cdot A.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Mat.identity(Q, 2).scale(rat(1, 5));
  print(m);
  print('det = ${m.determinant}');
}
Output
1/5 0
0 1/5
det = 1/25
applymethod
Vec<T> apply(Vec<T> v)

The matrix–vector product A v, with v as a column vector of dimension m. Throws RangeError when v is too short.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The rotation with rational entries (3/5, 4/5) carries (5, 0) to (3, 4).
  final r = Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]);
  print('R (5, 0) = ${r.apply(qv([5, 0]))}');
  print('R (1, 1) = ${r.apply(qv([1, 1]))}');
}
Output
R (5, 0) = [3, 4]
R (1, 1) = [-1/5, 7/5]
rowmethod
Vec<T> row(int i)

Row i as a vector.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Mat(Q, [[rat(1), rat(2), rat(3)], [rat(4), rat(5), rat(6)]]);
  print('row 0: ${m.row(0)}, row 1: ${m.row(1)}');
}
Output
row 0: [1, 2, 3], row 1: [4, 5, 6]
columnmethod
Vec<T> column(int j)

Column j as a vector.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = Mat(Q, [[rat(1), rat(2), rat(3)], [rat(4), rat(5), rat(6)]]);
  for (var j = 0; j < 3; j++) print('column $j: ${m.column(j)}');
}
Output
column 0: [1, 4]
column 1: [2, 5]
column 2: [3, 6]
solvemethod
Vec<T>? solve(Vec<T> b)

The exact solution x of A x = b, or null when A is singular. Throws StateError when A is not square.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Hilbert's 3 × 3 matrix: exact solve, no rounding.
  final h = Mat(Q, [for (var i = 1; i <= 3; i++) [for (var j = 1; j <= 3; j++) rat(1, i + j - 1)]]);
  final x = h.solve(qv([1, 1, 1]))!;
  print('x = $x');
  print('H x = ${h.apply(x)}');
  final s = Mat(Q, [[rat(1), rat(2)], [rat(2), rat(4)]]);
  print('singular: ${s.solve(qv([1, 1]))}');
}
Output
x = [3, -24, 30]
H x = [1, 1, 1]
singular: null
toStringmethod
String toString()

One line per row, entries formatted by the field and separated by spaces.

Operators

operator *operator
Mat<T> operator *(Mat<T> o)

The matrix product this · o: an n × o.m matrix. Needs m equal to o.n; otherwise it throws RangeError or gives a wrong result.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Two rational rotations compose to a rational rotation.
  final a = Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]);
  print('A² =\n${a * a}');
  print('A·A⁻¹ == I: ${a * a.inverse == Mat.identity(Q, 2)}');
}
Output
A² =
-7/25 -24/25
24/25 -7/25
A·A⁻¹ == I: true
operator +operator
Mat<T> operator +(Mat<T> o)

The entrywise sum. o must have the same shape.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = Mat(Q, [[rat(1), rat(2)], [rat(3), rat(4)]]);
  print('A + Aᵀ =\n${a + a.transpose}');
}
Output
A + Aᵀ =
2 5
5 8
operator -operator
Mat<T> operator -(Mat<T> o)

The entrywise difference. o must have the same shape.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = Mat(Q, [[rat(1), rat(2)], [rat(3), rat(4)]]);
  print('A − Aᵀ =\n${a - a.transpose}');
}
Output
A − Aᵀ =
0 -1
1 0
operator ==operator
bool operator ==(Object other)

Exact equality: other is a Mat of the same type and shape with equal entries in the field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]);
  print('RᵀR == I: ${r.transpose * r == Mat.identity(Q, 2)}');
}
Output
RᵀR == I: true
final class SymmetricForm<T>

A symmetric bilinear form B(u, v) = u^{T} M v: the metric of a geometry. Quadrance is Q(A, B) = B(B - A, B - A), spread is s(u, v) = 1 - B(u, v)^{2} / (B(u, u) B(v, v)) (Wildberger, Divine Proportions, ch. 3 and ch. 30–31 for general metrics).

The constructors SymmetricForm.blue, SymmetricForm.red and SymmetricForm.green give the three planar geometries of chromogeometry; SymmetricForm.diagonal gives Minkowski and other diagonal metrics. A vector v with B(v, v) = 0 is null (isNull); spreads, crosses and reflections involving a null vector are undefined and throw.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The same two vectors in the three chromogeometries.
  final u = qv([3, 1]), v = qv([1, 2]);
  for (final (name, f) in [('blue', SymmetricForm.blue(Q)), ('red', SymmetricForm.red(Q)), ('green', SymmetricForm.green(Q))]) {
    print('$name: quadrance(u) = ${f.norm(u)}, spread(u, v) = ${f.spread(u, v)}');
  }
}
Output
blue: quadrance(u) = 10, spread(u, v) = 1/2
red: quadrance(u) = 8, spread(u, v) = 25/24
green: quadrance(u) = 6, spread(u, v) = -25/24

Constructors

SymmetricFormconstructor
SymmetricForm(this.matrix)

The form with matrix matrix. Throws ArgumentError when matrix is not square or not symmetric. A degenerate matrix (\det M = 0) is accepted, but orthogonalBasis and the reflection decompositions need \det M \ne 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Any symmetric matrix is a metric: here B(u, v) = 2u₁v₁ + u₁v₂ + u₂v₁ + 3u₂v₂.
  final form = SymmetricForm(Mat(Q, [[rat(2), rat(1)], [rat(1), rat(3)]]));
  final u = qv([1, 0]), v = qv([0, 1]);
  print('Q(u) = ${form.norm(u)}, Q(v) = ${form.norm(v)}, B(u, v) = ${form.apply(u, v)}');
  print('spread(u, v) = ${form.spread(u, v)}');
}
Output
Q(u) = 2, Q(v) = 3, B(u, v) = 1
spread(u, v) = 5/6
factory SymmetricForm.blue(ScalarField<T> f, [int n = 2])

The blue (Euclidean) form x_{1}^{2} + \cdots + x_{n}^{2} on F^{n}, M = I. n defaults to 2.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The Euclidean form in 2 and 3 dimensions.
  final b2 = SymmetricForm.blue(Q), b3 = SymmetricForm.blue(Q, 3);
  print('Q((3, 4)) = ${b2.norm(qv([3, 4]))}');
  print('Q((1, 2, 2)) = ${b3.norm(qv([1, 2, 2]))}');
}
Output
Q((3, 4)) = 25
Q((1, 2, 2)) = 9
factory SymmetricForm.red(ScalarField<T> f)

The planar red form x^{2} - y^{2} (Wildberger's chromogeometry; 1 + 1 Minkowski space), M = \operatorname{diag}(1, -1).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final red = SymmetricForm.red(Q);
  print('Q_r((3, 4)) = ${red.norm(qv([3, 4]))}');
  print('(1, 1) is null in red: ${red.isNull(qv([1, 1]))}');
}
Output
Q_r((3, 4)) = -7
(1, 1) is null in red: true
factory SymmetricForm.green(ScalarField<T> f)

The planar green form 2xy (chromogeometry; Minkowski space in null coordinates), M = \begin{bmatrix}0 & 1 \\ 1 & 0\end{bmatrix}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final green = SymmetricForm.green(Q);
  print('Q_g((3, 4)) = ${green.norm(qv([3, 4]))}');
  print('(1, 0) is null in green: ${green.isNull(qv([1, 0]))}');
}
Output
Q_g((3, 4)) = 24
(1, 0) is null in green: true
factory SymmetricForm.diagonal(ScalarField<T> f, List<int> d)

The diagonal form \operatorname{diag}(d_{1}, \ldots, d_{n}) from integers d, e.g. [-1, 1, 1, 1] for Minkowski space-time.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Minkowski space-time diag(−1, 1, 1, 1): light-like vectors have quadrance 0.
  final eta = SymmetricForm.diagonal(Q, [-1, 1, 1, 1]);
  print('light ray (1,1,0,0): ${eta.norm(qv([1, 1, 0, 0]))}');
  print('at rest (1,0,0,0):   ${eta.norm(qv([1, 0, 0, 0]))}');
  print('space (0,3,4,0):     ${eta.norm(qv([0, 3, 4, 0]))}');
}
Output
light ray (1,1,0,0): 0
at rest (1,0,0,0):   -1
space (0,3,4,0):     25

Properties

matrixfield
final Mat<T> matrix

The symmetric matrix M of the form.

fieldgetter
ScalarField<T> get field

The field the entries live in.

dimgetter
int get dim

The dimension n of the space the form acts on.

T get determinant

The determinant \det M of the form's matrix; zero exactly when the form is degenerate.

Methods

applymethod
T apply(Vec<T> u, Vec<T> v)

The value B(u, v) = u^{T} M v. Both vectors must have dimension dim. Diagonal forms take a faster path.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q), red = SymmetricForm.red(Q);
  final u = qv([2, 1]), v = qv([1, 3]);
  print('blue B(u, v) = ${blue.apply(u, v)}');
  print('red  B(u, v) = ${red.apply(u, v)}');
}
Output
blue B(u, v) = 5
red  B(u, v) = -1
normmethod
T norm(Vec<T> v)

The quadrance of a vector, Q(v) = B(v, v). It may be zero or, for an indefinite form, negative.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final f = SymmetricForm.blue(Q);
  print('Q((1/2, 1/3)) = ${f.norm(qv(['1/2', '1/3']))}');
  print('in doubles: ${0.5 * 0.5 + (1 / 3) * (1 / 3)}');
}
Output
Q((1/2, 1/3)) = 13/36
in doubles: 0.3611111111111111
quadrancemethod
T quadrance(Vec<T> a, Vec<T> b)

The quadrance between the points a and b, Q(A, B) = B(B - A, B - A).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Quadrance replaces distance: Q(A, B) = (x₂ − x₁)² + (y₂ − y₁)².
  final blue = SymmetricForm.blue(Q);
  final a = qv([1, 1]), b = qv([4, 5]);
  print('Q(A, B) = ${blue.quadrance(a, b)}');
  print('red: ${SymmetricForm.red(Q).quadrance(a, b)}, green: ${SymmetricForm.green(Q).quadrance(a, b)}');
}
Output
Q(A, B) = 25
red: -7, green: 24
isNullmethod
bool isNull(Vec<T> v)

Whether v is a null (isotropic) vector: B(v, v) = 0. Lines with null directions have no spread. The zero vector is null for every form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final red = SymmetricForm.red(Q);
  for (final v in [qv([1, 1]), qv([1, -1]), qv([2, 1])]) print('$v null in red: ${red.isNull(v)}');
}
Output
[1, 1] null in red: true
[1, -1] null in red: true
[2, 1] null in red: false
bool perpendicular(Vec<T> u, Vec<T> v)

Whether u and v are perpendicular in this metric: B(u, v) = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q), red = SymmetricForm.red(Q);
  final u = qv([1, 2]), v = qv([2, 1]);
  print('blue ⊥: ${blue.perpendicular(u, v)}, red ⊥: ${red.perpendicular(u, v)}');
  print('blue ⊥ (2, −1): ${blue.perpendicular(u, qv([2, -1]))}');
}
Output
blue ⊥: false, red ⊥: true
blue ⊥ (2, −1): true
crossmethod
T cross(Vec<T> u, Vec<T> v)

The cross c(u, v) = B(u, v)^{2} / (B(u, u) B(v, v)) (classically \cos^{2}\theta): 1 for parallel, 0 for perpendicular. Throws StateError when u or v is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The cross c = B(u,v)²/(Q(u)Q(v)): 1 for parallel lines, 0 for perpendicular ones.
  final f = SymmetricForm.blue(Q);
  final u = qv([1, 0]), v = qv([3, 4]);
  print('c(u, v) = ${f.cross(u, v)},  s + c = ${f.spread(u, v) + f.cross(u, v)}');
}
Output
c(u, v) = 9/25,  s + c = 1
spreadmethod
T spread(Vec<T> u, Vec<T> v)

The spread s(u, v) = 1 - c(u, v) = \frac{Q(u)Q(v) - B(u, v)^{2}}{Q(u)Q(v)} (classically \sin^{2}\theta): 0 for parallel, 1 for perpendicular. Depends only on the lines, not on the direction vectors chosen. One division. Throws StateError when u or v is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  print('spread((1,0), (1,1)) = ${blue.spread(qv([1, 0]), qv([1, 1]))}');
  print('spread((1,0), (0,1)) = ${blue.spread(qv([1, 0]), qv([0, 1]))}');
  print('spread((1,0), (2,0)) = ${blue.spread(qv([1, 0]), qv([2, 0]))}');
  print('spread((3,4), (4,3)) = ${blue.spread(qv([3, 4]), qv([4, 3]))}');
}
Output
spread((1,0), (1,1)) = 1/2
spread((1,0), (0,1)) = 1
spread((1,0), (2,0)) = 0
spread((3,4), (4,3)) = 49/625
twistmethod
T twist(Vec<T> u, Vec<T> v)

The twist t = s / c (classically \tan^{2}\theta). Throws StateError when u or v is null; when they are perpendicular (c = 0) the field's division by zero fails (over Q, UnsupportedError).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The twist t = s/c, the rational replacement for tan².
  final f = SymmetricForm.blue(Q);
  print('t((1,0), (3,4)) = ${f.twist(qv([1, 0]), qv([3, 4]))}');
  print('t((1,0), (1,1)) = ${f.twist(qv([1, 0]), qv([1, 1]))}');
}
Output
t((1,0), (3,4)) = 16/9
t((1,0), (1,1)) = 1
spreadAtmethod
T spreadAt(Vec<T> a, Vec<T> b, Vec<T> c)

The spread at the vertex a between the lines from a towards b and towards c. Throws StateError when either side is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The spread at each vertex of the 3-4-5 triangle.
  final f = SymmetricForm.blue(Q);
  final a = qv([0, 0]), b = qv([4, 0]), c = qv([0, 3]);
  print('at A: ${f.spreadAt(a, b, c)}, at B: ${f.spreadAt(b, a, c)}, at C: ${f.spreadAt(c, a, b)}');
}
Output
at A: 1, at B: 9/25, at C: 16/25
reflectmethod
Vec<T> reflect(Vec<T> x, Vec<T> v)

The reflection of x in the hyperplane through the origin B-perpendicular to v: x - \frac{2B(x, v)}{B(v, v)} \cdot v. Always exact: every isometry of a non-degenerate form is a product of these (Cartan–Dieudonné). v must be non-null; for a null v the field's division by zero fails (over Q, UnsupportedError).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  // Reflect (2, 1) in the line through the origin with direction (1, 1).
  print('reflection of (2, 1): ${blue.reflect(qv([2, 1]), qv([1, 1]))}');
}
Output
reflection of (2, 1): [-1, -2]
Mat<T> reflectionMatrix(Vec<T> v)

The matrix of reflect in the normal v: I - 2 v (Mv)ᵀ / B(v, v), so that reflectionMatrix(v).apply(x) equals reflect(x, v). Throws StateError when v is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Reflection in the line perpendicular to v: I − 2v(Mv)ᵀ/B(v, v).
  final f = SymmetricForm.blue(Q);
  final r = f.reflectionMatrix(qv([1, 2]));
  print(r);
  print('isometry: ${f.isIsometry(r)}, R² = I: ${r * r == Mat.identity(Q, 2)}');
}
Output
3/5 -4/5
-4/5 -3/5
isometry: true, R² = I: true
bool isIsometry(Mat<T> a)

Whether the matrix a is an isometry of this form, A^{T} M A = M, tested exactly. Isometries keep every quadrance and spread of the metric.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q), red = SymmetricForm.red(Q);
  final rot = Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]);
  final boost = Mat(Q, [[rat(5, 4), rat(3, 4)], [rat(3, 4), rat(5, 4)]]);
  print('rotation: blue ${blue.isIsometry(rot)}, red ${red.isIsometry(rot)}');
  print('boost:    blue ${blue.isIsometry(boost)}, red ${red.isIsometry(boost)}');
}
Output
rotation: blue true, red false
boost:    blue false, red true
toStringmethod
String toString()

The matrix, labelled, one row per line.

class

Gram

final class Gram<T>

The Gram matrix G = V^{T} M V of vectors v_{0} \cdots v_{k - 1} in a metric (G_{ij} = B(v_{i}, v_{j})), and the rational trigonometry read off its minors. Computed once; every measure afterwards is a few field operations on G.

Vectors are named by their index in vectors. A measure that divides by the quadrance of a null vector (G_{ii} = 0) throws StateError.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The Gram matrix of three vectors: every quadrance and spread among them comes from it.
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([1, 0, 0]), qv([1, 1, 0]), qv([1, 1, 1])]);
  print(g.matrix);
}
Output
1 1 1
1 2 2
1 2 3

Constructors

Gramconstructor
Gram(this.form, List<Vec<T>> vectors)

The Gram matrix of vectors in the metric form: k^{2} values B(v_{i}, v_{j}), computed once.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final g = Gram(SymmetricForm.red(Q), [qv([2, 1]), qv([1, 3])]);
  print('red Gram matrix:\n${g.matrix}');
}
Output
red Gram matrix:
3 -1
-1 -8

Properties

formfield
final SymmetricForm<T> form

The metric the dot products are taken in.

vectorsfield
final List<Vec<T>> vectors

The vectors v_{0} \cdots v_{k - 1}, unmodifiable.

gfield
final List<List<T>> g

G as unmodifiable rows: g[j] is B(v_{i}, v_{j}).

fgetter
ScalarField<T> get f

The field the entries live in.

sizegetter
int get size

The number k of vectors, so G is k \times k.

matrixgetter
Mat<T> get matrix

G as a Mat.

T get determinant

The full Gram determinant \det G; zero when the vectors are linearly dependent.

Methods

dotmethod
T dot(int i, int j)

The dot product B(v_{i}, v_{j}) = G_{ij} of vectors i and j.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final g = Gram(SymmetricForm.blue(Q), [qv([3, 4]), qv([1, 2])]);
  print('B(v0, v1) = ${g.dot(0, 1)}');
}
Output
B(v0, v1) = 11
quadrancemethod
T quadrance(int i)

The quadrance Q(v_{i}) = G_{ii} of vector i.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final g = Gram(SymmetricForm.blue(Q), [qv([3, 4]), qv([1, 2])]);
  print('Q(v0) = ${g.quadrance(0)}, Q(v1) = ${g.quadrance(1)}');
}
Output
Q(v0) = 25, Q(v1) = 5
minormethod
T minor(List<int> s)

The principal minor \det G_{S} for the index set s (the "quadrume"-type invariant of those vectors: for the blue form, the squared k-volume of the parallelotope they span). It is zero when those vectors are linearly dependent. The empty minor is 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Principal minors: squared areas and volumes of the parallelotopes spanned.
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([1, 0, 0]), qv([1, 2, 0]), qv([0, 1, 3])]);
  print('det G_{0,1} = ${g.minor([0, 1])} (area² of the parallelogram = 2² = 4)');
  print('det G = ${g.minor([0, 1, 2])} (volume² = 6² = 36)');
}
Output
det G_{0,1} = 4 (area² of the parallelogram = 2² = 4)
det G = 36 (volume² = 6² = 36)
crossmethod
T cross(int i, int j)

The cross c(v_{i}, v_{j}) = G_{ij}^{2} / (G_{ii} G_{jj}) (classically \cos^{2}\theta). Throws StateError when v_{i} or v_{j} is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final g = Gram(SymmetricForm.blue(Q), [qv([1, 0]), qv([3, 4])]);
  print('c = ${g.cross(0, 1)}');
}
Output
c = 9/25
spreadmethod
T spread(int i, int j)

The spread s(v_{i}, v_{j}) = \det G_{ij} / (G_{ii} G_{jj}), the 2 \times 2 Gram minor over the diagonal: no subtraction of nearly equal numbers after the division, so the same formula is also the accurate one in floating point. Throws StateError when v_{i} or v_{j} is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final g = Gram(SymmetricForm.blue(Q), [qv([1, 0]), qv([3, 4])]);
  print('s = ${g.spread(0, 1)}');
}
Output
s = 16/25
kSpreadmethod
T kSpread(List<int> s)

The k-spread \det G_{S} / \prod_{i \in S} G_{ii} of the lines through the vectors in s: 0 when they are dependent, 1 when they are mutually perpendicular. k = 2 is the spread, k = 3 in three dimensions is Notowidigdo–Wildberger's solid spread (the rational solid angle); other k and dimensions are our extension (the Hadamard ratio). Throws StateError when any of the vectors is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The 3-spread (solid spread) of the three coordinate axes is 1; of three coplanar vectors, 0.
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([1, 0, 0]), qv([0, 1, 0]), qv([0, 0, 1]), qv([1, 1, 0]), qv([1, 1, 1])]);
  print('axes: ${g.kSpread([0, 1, 2])}, coplanar: ${g.kSpread([0, 1, 3])}, (x, y, diagonal): ${g.kSpread([0, 1, 4])}');
}
Output
axes: 1, coplanar: 0, (x, y, diagonal): 1/3
T lineSubspaceSpread(int i, List<int> sub)

The spread between the line through v_{i} and the subspace spanned by the vectors in sub: \det G_{i \cup S} / (Q(v_{i}) \cdot \det G_{S}) (classically \sin^{2} of the angle between a line and a plane, …): 0 when v_{i} lies in the subspace, 1 when it is perpendicular to it. Throws StateError when the subspace is degenerate (\det G_{S} = 0: null or dependent vectors) or v_{i} is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The spread between the cube diagonal and the floor plane: 1/3.
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([1, 1, 1]), qv([1, 0, 0]), qv([0, 1, 0])]);
  print('spread(diagonal, xy-plane) = ${g.lineSubspaceSpread(0, [1, 2])}');
}
Output
spread(diagonal, xy-plane) = 1/3
T dihedralSpread(List<int> common, int a, int b)

The dihedral spread between the subspaces \operatorname{span}(C \cup \{a\}) and \operatorname{span}(C \cup \{b\}), which meet in \operatorname{span}(C): \det G_{C} \cdot \det G_{C \cup \{a, b\}} / (\det G_{C \cup \{a\}} \cdot \det G_{C \cup \{b\}}). With C a single vector in 3-D this is Notowidigdo–Wildberger's dihedral spread theorem (arXiv:1909.08814, Theorem 12); it is the spread between the components of a and b B-perpendicular to \operatorname{span}(C) (Desnanot–Jacobi), so it holds in every dimension and metric. common lists the indices of C; a and b are single indices. Throws StateError when either face is degenerate (\det G_{C \cup \{a\}} = 0 or \det G_{C \cup \{b\}} = 0).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The planes span(z, x) and span(z, x + y) meet along z with dihedral spread 1/2.
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([0, 0, 1]), qv([1, 0, 0]), qv([1, 1, 0])]);
  print('dihedral spread: ${g.dihedralSpread([0], 1, 2)}');
}
Output
dihedral spread: 1/2
T tripleSpreadResidual(int i, int j, int l)

The Triple spread residual (s_{1} + s_{2} + s_{3})^{2} - 2(s_{1}^{2} + s_{2}^{2} + s_{3}^{2}) - 4s_{1}s_{2}s_{3} of the three spreads among v_{i}, v_{j}, v_{l}, computed from the spreads. It is zero exactly when the Triple spread formula holds, which is the case for three coplanar lines (always in 2-D). Throws StateError when any of the three vectors is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Three coplanar lines satisfy the triple spread formula; three independent ones don't.
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([1, 0, 0]), qv([1, 2, 0]), qv([3, 1, 0]), qv([0, 0, 1])]);
  print('coplanar: ${g.tripleSpreadResidual(0, 1, 2)}, not: ${g.tripleSpreadResidual(0, 1, 3)}');
}
Output
coplanar: 0, not: -16/25
T tripleSpreadResidualFromGram(int i, int j, int l)

The same residual from the Gram matrix alone: \det G_{3} \cdot (4 b_{ij} b_{il} b_{jl} - \det G_{3}) / (a_{i} a_{j} a_{l})^{2}, with G_{3} the 3 \times 3 Gram matrix of the three vectors (Goh–Wildberger, Theorem 3). It vanishes when the three lines are coplanar, because \det G_{3} does: the Triple spread formula is the rank condition on the Gram matrix. Equal to tripleSpreadResidual. Throws StateError when any of the three vectors is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final g = Gram(SymmetricForm.blue(Q, 3), [qv([1, 0, 0]), qv([1, 2, 0]), qv([0, 0, 1])]);
  print('from spreads: ${g.tripleSpreadResidual(0, 1, 2)}, from the Gram matrix: ${g.tripleSpreadResidualFromGram(0, 1, 2)}');
}
Output
from spreads: -16/25, from the Gram matrix: -16/25
extension MetricMatrixTrig<T> on SymmetricForm<T>

The metric-matrix forms of quadrance and spread, the B-vector product, and exact rotations of any metric.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  print('spread by wedge: ${blue.spreadByWedge(qv([1, 0]), qv([1, 2]))}, by the usual formula: ${blue.spread(qv([1, 0]), qv([1, 2]))}');
}
Output
spread by wedge: 4/5, by the usual formula: 4/5

Methods

grammethod
Gram<T> gram(List<Vec<T>> vs)

The Gram matrix of vs in this metric, as a Gram.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final g = SymmetricForm.blue(Q).gram([qv([1, 2]), qv([3, 1])]);
  print(g.matrix);
}
Output
5 5
5 10
T spreadByWedge(Vec<T> u, Vec<T> v)

The spread of two planar vectors as \det M \cdot (u \wedge v)^{2} / (Q(u)Q(v)) (Goh–Wildberger, p. 7, for a general 2-D form; the blue, red and green spreads of "Chromogeometry" are the cases \det M = 1, -1, -1). Cauchy–Binet makes this equal to SymmetricForm.spread; it squares a determinant instead of subtracting two products. Throws StateError unless the form is 2-D, or when u or v is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  for (final (n, f) in [('blue', SymmetricForm.blue(Q)), ('red', SymmetricForm.red(Q)), ('green', SymmetricForm.green(Q))]) {
    print('$n: ${f.spreadByWedge(qv([2, 1]), qv([1, 3]))}');
  }
}
Output
blue: 1/2
red: 25/24
green: -25/24
Vec<T> vectorProduct(Vec<T> u, Vec<T> v)

The B-vector product u \times_{B} v = \operatorname{adj}(M)(u \times v) in three dimensions (Notowidigdo–Wildberger, arXiv:1903.08330, §2): B-perpendicular to u and v, with B(w, u \times_{B} v) = \det M \cdot \det[w u v]. For the blue form it is the ordinary cross product. Throws StateError unless the form is 3-D.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final f = SymmetricForm.diagonal(Q, [1, 1, -1]);
  final u = qv([1, 0, 2]), v = qv([0, 1, 3]);
  final w = f.vectorProduct(u, v);
  print('u ×_B v = $w, B-perpendicular: ${f.apply(w, u)}, ${f.apply(w, v)}');
}
Output
u ×_B v = [2, 3, 1], B-perpendicular: 0, 0
T spreadByVectorProduct(Vec<T> u, Vec<T> v)

The spread in three dimensions by Lagrange's identity: Q(u \times_{B} v) / (\det M \cdot Q(u)Q(v)), equal to SymmetricForm.spread. Throws StateError unless the form is 3-D, or when u or v is null. Needs \det M \ne 0; for a degenerate form the field's division by zero fails.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final f = SymmetricForm.blue(Q, 3);
  print('${f.spreadByVectorProduct(qv([1, 0, 0]), qv([1, 1, 1]))} = ${f.spread(qv([1, 0, 0]), qv([1, 1, 1]))}');
}
Output
2/3 = 2/3
Mat<T>? cayleyRotation(Mat<T> k)

The Cayley rotation R = (M - K)^{-1}(M + K) for a skew-symmetric K: an exact isometry of this metric (R^{T} M R = M) with \det R = 1, rational in the entries of K, over any field. Every rotation without the eigenvalue -1 arises exactly once. Returns null when M - K is singular; throws ArgumentError when k is not skew-symmetric (K^{T} = -K, zero diagonal). In 2-D, K = t \cdot \begin{bmatrix}0 & 1 \\ -1 & 0\end{bmatrix} gives the one-parameter rotation group of the metric (for the blue form, the rational parametrisation of the unit circle); in 3-D, K = [\omega]_{x} gives Euler–Rodrigues. Composition is matrix multiplication, so a chain of rotations stays exact.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // (M − K)⁻¹(M + K) for skew K: an exact rotation of the metric.
  final blue = SymmetricForm.blue(Q, 3);
  final k = Mat(Q, [[rat(0), rat(1), rat(0)], [rat(-1), rat(0), rat(2)], [rat(0), rat(-2), rat(0)]]);
  final r = blue.cayleyRotation(k)!;
  print(r);
  print('isometry ${blue.isIsometry(r)}, det ${r.determinant}');
}
Output
2/3 1/3 2/3
-1/3 -2/3 2/3
2/3 -2/3 -1/3
isometry true, det 1
rotationmethod
Mat<T>? rotation(T t)

The planar rotation of this metric with parameter t: cayleyRotation of t \cdot \begin{bmatrix}0 & 1 \\ -1 & 0\end{bmatrix}. For the blue form, rotation(1) is the quarter turn sending (1, 0) to (0, -1), and t runs over the rational points of the unit circle. Combine parameters with addRotationParameters. Returns null when M - K is singular (for the red form, t = \pm1); throws StateError unless the form is 2-D.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q), red = SymmetricForm.red(Q);
  print('blue rotation(1/2):\n${blue.rotation(rat(1, 2))}');
  print('red rotation(1/2):\n${red.rotation(rat(1, 2))}');
}
Output
blue rotation(1/2):
3/5 4/5
-4/5 3/5
red rotation(1/2):
5/3 4/3
4/3 5/3
T rotationSpread(Mat<T> r)

The spread every non-null vector makes with its image under a planar rotation R of this metric: 1 - \frac{(\operatorname{tr} R)^{2}}{4} (classically \sin^{2}\theta = 1 - \cos^{2}\theta with \operatorname{tr} R = 2 \cos \theta). Our derivation: in 2-D, R = aI + bJ with MJ skew, so B(v, Rv) = a \cdot Q(v) and the cross is a^{2} = (\operatorname{tr} R / 2)^{2}. Only the trace of r is read; that r is a planar rotation of this metric is not checked. For the blue rotation(1) (a quarter turn) it is 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  final r = blue.rotation(rat(1, 2))!;
  print('spread of the turn: ${blue.rotationSpread(r)}; check: ${blue.spread(qv([1, 0]), r.apply(qv([1, 0])))}');
}
Output
spread of the turn: 16/25; check: 16/25
abstract final class SpreadPolynomials

Spread polynomials as matrix powers (Wildberger, Divine Proportions, 2005; Goh–Wildberger, arXiv:0911.1025).

S_{n}(s) is the spread of n copies of a spread s laid side by side (classically \sin^{2}(n\theta) when s = \sin^{2}\theta), so S_{0} = 0, S_{1}(s) = s, S_{2}(s) = 4s(1 - s). Both functions are static; the class has no instances.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Spread polynomials Sₙ(s): the spread of n times an angle of spread s, as polynomials with integer coefficients.
  for (var n = 1; n <= 5; n++) print('S$n(1/4) = ${SpreadPolynomials.value(Q, n, rat(1, 4))}');
  print('period of s = 3 in ℤ/13: ${SpreadPolynomials.period(PrimeField(13), 3)}');
        for (var n = 1; n <= 4; n++)
          {'label': 'S$n', 'points': [for (var i = 0; i <= 50; i++) [i / 50, SpreadPolynomials.value(Q, n, rat(i, 50)).toDouble()]]}
      ]})}');
}
Output
S1(1/4) = 1/4
S2(1/4) = 3/4
S3(1/4) = 1
S4(1/4) = 3/4
S5(1/4) = 1/4
period of s = 3 in ℤ/13: 14

Static

valuestaticmethod
static T value<T>(ScalarField<T> f, int n, T s)

S_{n}(s) in O(\log n) field operations: S_{n}(s) = \frac{1 - T_{n}(1 - 2s)}{2} (arXiv:math/0612499, p. 20), with the Chebyshev value T_{n}(x) read off \begin{bmatrix} 2x & -1 \\ 1 & 0 \end{bmatrix}^{n-1} (standard). Over \mathbb{Z}/p this evaluates S at n = 10^{18} in microseconds.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Spread 1/4 is a 30° turn: twice it is 3/4, three times a right angle (1), six times a straight line (0).
  for (final n in [1, 2, 3, 4, 6]) {
    print('S$n(1/4) = ${SpreadPolynomials.value(Q, n, rat(1, 4))}');
  }
}
Output
S1(1/4) = 1/4
S2(1/4) = 3/4
S3(1/4) = 1
S4(1/4) = 3/4
S6(1/4) = 0
periodstaticmethod
static int period(PrimeField f, int s)

The spread period of s in \mathbb{Z}/p: the least m \ge 1 with S_{m}(s) = 0, so that S_{n}(s) = 0 exactly when m \mid n. Goh and Wildberger's Spread periodicity theorem (arXiv:0911.1025, Theorem 11) says m divides p - 1 or p + 1, because it is the order of a rotation in a group of that size; we find it as an element order, by fast evaluation at the divisors of p \pm 1, in O(\log^{2} p) operations instead of O(p). s is a residue of f given as an int; for example the period of 3 in \mathbb{Z}/11 is 6, and the period of 0 is 1. Throws StateError when neither p - 1 nor p + 1 is a multiple of the period (the theorem rules this out for every s in \mathbb{Z}/p).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final f = PrimeField(13);
  for (final s in [1, 2, 3, 4, 5]) {
    print('spread $s in F13 has period ${SpreadPolynomials.period(f, s)}');
  }
}
Output
spread 1 in F13 has period 2
spread 2 in F13 has period 7
spread 3 in F13 has period 14
spread 4 in F13 has period 3
spread 5 in F13 has period 7
extension ChromoMatrices<T> on Chromogeometry<T>

Chromogeometry as matrices. Wildberger defines each colour's quadrance as the determinant of a vector and its perpendicular: Q_{b} = \det\begin{bmatrix}a & b \\ -b & a\end{bmatrix}, Q_{r} = \det\begin{bmatrix}a & b \\ b & a\end{bmatrix}, Q_{g} = \det\begin{bmatrix}a & b \\ -a & b\end{bmatrix} ("Chromogeometry and relativistic conics", KoG 13 (2009), eqs. (1)–(3)). The three perpendicularity maps are matrices J_{b}, J_{r}, J_{g} with J_{b}^{2} = -I, J_{r}^{2} = J_{g}^{2} = I and J_{b} J_{r} = J_{g}: the units i, j, k of the split quaternions, which is all of M_{2}(F) (our observation). And Q_{b}^{2} = Q_{r}^{2} + Q_{g}^{2} is \det(v v^{T}) = 0 written in the basis I, \operatorname{diag}(1, -1), [[0, 1], [1, 0]] of symmetric matrices, where det is the Minkowski form \frac{Q_{b}^{2} - Q_{r}^{2} - Q_{g}^{2}}{4} (our observation).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Chromogeometry(Q);
  for (final col in Colour.values) print('$col J:\n${c.perpendicularMap(col)}');
}
Output
Colour.blue J:
0 -1
1 0
Colour.red J:
0 1
1 0
Colour.green J:
-1 0
0 1

Methods

Mat<T> perpendicularMap(Colour c)

The perpendicularity map J_{c} of the colour c, acting on column vectors, so that J_{c} v is c-perpendicular to v: blue \begin{bmatrix}0 & -1 \\ 1 & 0\end{bmatrix}, red [[0, 1], [1, 0]], green \begin{bmatrix}-1 & 0 \\ 0 & 1\end{bmatrix}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Chromogeometry(Q);
  final v = qv([3, 1]);
  for (final col in Colour.values) {
    final w = c.perpendicularMap(col).apply(v);
    print('$col: J v = $w, perpendicular: ${c.form(col).perpendicular(v, w)}');
  }
}
Output
Colour.blue: J v = [-1, 3], perpendicular: true
Colour.red: J v = [1, 3], perpendicular: true
Colour.green: J v = [-3, 1], perpendicular: true
T quadranceByDeterminant(Colour c, Vec<T> v)

The quadrance Q_{c}(v) = \det[v, J_{c} v] of the colour c (Wildberger's definition, a signed area): x^{2} + y^{2} for blue, x^{2} - y^{2} for red, 2xy for green. For v = (3, 1) these are 10, 8 and 6.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final c = Chromogeometry(Q);
  final v = qv([3, 1]);
  for (final col in Colour.values) print('$col: det[v, Jv] = ${c.quadranceByDeterminant(col, v)}, Q = ${c.form(col).norm(v)}');
}
Output
Colour.blue: det[v, Jv] = 10, Q = 10
Colour.red: det[v, Jv] = 8, Q = 8
Colour.green: det[v, Jv] = 6, Q = 6
class

Line

final class Line<T>

The line \langle a: b: c\rangle, the points (x, y) with ax + by + c = 0 (a and b not both zero).

The coefficients are a proportion: ⟨ka: kb: kc⟩ is the same line for any k \ne 0, so compare lines with sameAs, not by coefficients. Joins and meets are exact in field, and the metric is passed only to the operations that need one (perpendicularThrough, foot, isNull, lineSpread); the rest are metric-free.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final l = Line.join(qv([0, 0]), qv([2, 1]));
  final m = Line.join(qv([0, 3]), qv([3, 0]));
  print('l: $l');
  print('m: $m');
  print('l meets m at ${l.meet(m)}');
  print('(4, 2) on l: ${l.contains(qv([4, 2]))}');
}
Output
l: ⟨-1 : 2 : 0⟩
m: ⟨3 : 3 : -9⟩
l meets m at [2, 1]
(4, 2) on l: true

Constructors

Lineconstructor
Line(this.field, this.a, this.b, this.c)

The line ax + by + c = 0 over field. Throws ArgumentError when a and b are both zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The line 2x − 3y + 6 = 0 as the proportion ⟨2 : −3 : 6⟩.
  final l = Line(Q, rat(2), rat(-3), rat(6));
  print('l = $l, direction ${l.direction}, normal ${l.normal}');
  print('(0, 2) on l: ${l.contains(qv([0, 2]))}');
}
Output
l = ⟨2 : -3 : 6⟩, direction [3, 2], normal [2, -3]
(0, 2) on l: true
Line.joinfactory
factory Line.join(Vec<T> p, Vec<T> q)

The line through two distinct planar points p and q. Throws ArgumentError when they are equal.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.join(qv([1, 2]), qv([4, 8]));
  print('line through (1, 2) and (4, 8): $l');
  print('contains (7, 14): ${l.contains(qv([7, 14]))}');
}
Output
line through (1, 2) and (4, 8): ⟨-6 : 3 : 0⟩
contains (7, 14): true
factory Line.through(Vec<T> p, Vec<T> d)

The line through the point p with direction d. Throws ArgumentError when d is zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.through(qv([1, 1]), qv([2, 3]));
  print('through (1,1) with direction (2,3): $l');
  print('(3, 4) on it: ${l.contains(qv([3, 4]))}');
}
Output
through (1,1) with direction (2,3): ⟨-3 : 2 : 1⟩
(3, 4) on it: true

Properties

fieldfield
final ScalarField<T> field

The field the coefficients live in.

afield
final T a

The coefficients of ax + by + c = 0.

bfield
final T b

The coefficients of ax + by + c = 0.

cfield
final T c

The coefficients of ax + by + c = 0.

directiongetter
Vec<T> get direction

A direction vector (-b, a) along the line.

normalgetter
Vec<T> get normal

The vector (a, b), the Euclidean (blue) normal. In another metric use perpendicularDirection.

Methods

evaluatemethod
T evaluate(Vec<T> p)

The value a x + b y + c at the point p: zero exactly on the line. Its sign and size depend on the chosen coefficients, not only on the line.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The sign of ax + by + c tells which side of the line a point is on.
  final l = Line.join(qv([0, 0]), qv([1, 1]));
  for (final p in [qv([2, 2]), qv([0, 1]), qv([1, 0])]) print('l$p = ${l.evaluate(p)}');
}
Output
l[2, 2] = 0
l[0, 1] = 1
l[1, 0] = -1
containsmethod
bool contains(Vec<T> p)

Whether the point p lies on the line.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.join(qv([0, 0]), qv([3, 1]));
  print('(6, 2): ${l.contains(qv([6, 2]))}, (1/3, 1/9): ${l.contains(qv(['1/3', '1/9']))}, (1, 1): ${l.contains(qv([1, 1]))}');
}
Output
(6, 2): true, (1/3, 1/9): true, (1, 1): false
bool isParallelTo(Line<T> o)

Whether this line and o are parallel: ab′ - ba' = 0. A line is parallel to itself.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.join(qv([0, 0]), qv([1, 2]));
  print('parallel to (0,1)→(1,3): ${l.isParallelTo(Line.join(qv([0, 1]), qv([1, 3])))}');
  print('parallel to the x-axis: ${l.isParallelTo(Line.join(qv([0, 0]), qv([1, 0])))}');
}
Output
parallel to (0,1)→(1,3): true
parallel to the x-axis: false
meetmethod
Vec<T>? meet(Line<T> o)

The point where this line meets o; null when they are parallel (including when they are the same line).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.join(qv([0, 0]), qv([3, 1])), m = Line.join(qv([0, 2]), qv([2, 0]));
  print('meet: ${l.meet(m)}');
  print('parallel lines: ${l.meet(l.parallelThrough(qv([0, 5])))}');
}
Output
meet: [3/2, 1/2]
parallel lines: null
Line<T> parallelThrough(Vec<T> p)

The line through p parallel to this one.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.join(qv([0, 0]), qv([2, 1]));
  final p = l.parallelThrough(qv([0, 3]));
  print('parallel through (0, 3): $p, parallel: ${p.isParallelTo(l)}');
}
Output
parallel through (0, 3): ⟨1 : -2 : 6⟩, parallel: true
Line<T> perpendicularThrough(Vec<T> p, SymmetricForm<T> form)

The line through p perpendicular to this one in the planar metric form. For a null line (see isNull) this is the line through p parallel to it, since a null direction is perpendicular to itself.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // "Perpendicular" depends on the metric: blue, red and green give three different lines.
  final l = Line.join(qv([0, 0]), qv([2, 1]));
  for (final (n, f) in [('blue', SymmetricForm.blue(Q)), ('red', SymmetricForm.red(Q)), ('green', SymmetricForm.green(Q))]) {
    print('$n perpendicular through (1, 3): ${l.perpendicularThrough(qv([1, 3]), f)}');
  }
}
Output
blue perpendicular through (1, 3): ⟨2 : 1 : -5⟩
red perpendicular through (1, 3): ⟨2 : -1 : 1⟩
green perpendicular through (1, 3): ⟨1 : 2 : -7⟩
Vec<T> perpendicularDirection(SymmetricForm<T> form)

A direction w perpendicular to the line in the planar metric form, B(d, w) = 0 for d = direction: w = J (M d), with M the matrix of form and J the quarter turn (x, y) \mapsto (-y, x).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line.join(qv([0, 0]), qv([2, 1]));
  print('blue: ${l.perpendicularDirection(SymmetricForm.blue(Q))}');
  print('red:  ${l.perpendicularDirection(SymmetricForm.red(Q))}');
}
Output
blue: [1, -2]
red:  [-1, -2]
footmethod
Vec<T>? foot(Vec<T> p, SymmetricForm<T> form)

The foot of the altitude from p to this line in the planar metric form: where the perpendicular through p meets the line. Null when the line is null in form (the altitude is then parallel to it).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  final l = Line.join(qv([0, 0]), qv([4, 2]));
  final p = qv([1, 3]);
  final f = l.foot(p, blue)!;
  print('foot of the perpendicular from (1, 3): $f');
  print('quadrance to the line: ${blue.quadrance(p, f)}');
        'segments': [[-1, -0.5, 4, 2], [1, 3, f.x.toDouble(), f.y.toDouble()]],
        'points': [[1, 3, 'P'], [f.x.toDouble(), f.y.toDouble(), 'F']]})}');
}
Output
foot of the perpendicular from (1, 3): [2, 1]
quadrance to the line: 5
isNullmethod
bool isNull(SymmetricForm<T> form)

Whether the line's direction is null in form, Q(d) = 0, so spreads with this line are undefined. In the red metric the diagonals y = \pm x are null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // y = x is null in red geometry (a light ray): spreads with it are undefined.
  final diag = Line.join(qv([0, 0]), qv([1, 1]));
  print('blue null: ${diag.isNull(SymmetricForm.blue(Q))}, red null: ${diag.isNull(SymmetricForm.red(Q))}');
}
Output
blue null: false, red null: true
sameAsmethod
bool sameAs(Line<T> o)

Whether o is the same line: its \langle a: b: c\rangle is proportional to this one's.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final l = Line(Q, rat(1), rat(2), rat(3)), m = Line(Q, rat(-2), rat(-4), rat(-6));
  print('⟨1:2:3⟩ same as ⟨−2:−4:−6⟩: ${l.sameAs(m)}, equal objects: ${l == m}');
}
Output
⟨1:2:3⟩ same as ⟨−2:−4:−6⟩: true, equal objects: false
toStringmethod
String toString()

⟨a: b: c⟩ with the coefficients formatted by the field.

class

Centres

abstract final class Centres

Planar triangle centres in any metric, each the solution of a 2 \times 2 linear system, so a rational triangle has rational centres. The metric-dependent centres return null when the system is singular, which for a non-degenerate SymmetricForm means the vertices are collinear.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  final a = qv([0, 0]), b = qv([6, 0]), c = qv([2, 4]);
  final o = Centres.circumcentre(blue, a, b, c)!;
  final h = Centres.orthocentre(blue, a, b, c)!;
  final g = Centres.centroid(a, b, c);
  print('circumcentre $o, orthocentre $h, centroid $g');
  print('circumquadrance ${Centres.circumquadrance(blue, a, b, c)}');
        'polygons': [[[0, 0], [6, 0], [2, 4]]],
        'points': [[o.x.toDouble(), o.y.toDouble(), 'O'], [h.x.toDouble(), h.y.toDouble(), 'H'], [g.x.toDouble(), g.y.toDouble(), 'G']]})}');
}
Output
circumcentre [3, 1], orthocentre [2, 2], centroid [8/3, 4/3]
circumquadrance 10

Static

circumcentrestaticmethod
static Vec<T>? circumcentre<T>(SymmetricForm<T> form, Vec<T> a, Vec<T> b, Vec<T> c)

The circumcentre: the point at equal quadrance from a, b and c in the planar metric form. Null when there is no unique such point (collinear vertices).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final o = Centres.circumcentre(blue, qv([0, 0]), qv([4, 0]), qv([1, 3]))!;
  print('circumcentre: $o');
  print('equal quadrances: ${blue.quadrance(o, qv([0, 0]))}, ${blue.quadrance(o, qv([4, 0]))}, ${blue.quadrance(o, qv([1, 3]))}');
  print('collinear: ${Centres.circumcentre(blue, qv([0, 0]), qv([1, 1]), qv([2, 2]))}');
}
Output
circumcentre: [2, 1]
equal quadrances: 5, 5, 5
collinear: null
orthocentrestaticmethod
static Vec<T>? orthocentre<T>(SymmetricForm<T> form, Vec<T> a, Vec<T> b, Vec<T> c)

The orthocentre: the meet of the altitudes in the planar metric form, the X with B(X - A, C - B) = 0 and B(X - B, C - A) = 0. Null when that system is singular (collinear vertices).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final a = qv([0, 0]), b = qv([4, 0]), c = qv([1, 3]);
  print('blue orthocentre: ${Centres.orthocentre(blue, a, b, c)}');
  print('red orthocentre:  ${Centres.orthocentre(SymmetricForm.red(Q), a, b, c)}');
}
Output
blue orthocentre: [1, 1]
red orthocentre:  [1, -1]
centroidstaticmethod
static Vec<T> centroid<T>(Vec<T> a, Vec<T> b, Vec<T> c)

The centroid \frac{A + B + C}{3}. Metric-free. In characteristic 3, where 3 = 0, it throws the field's division error.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  print('centroid: ${Centres.centroid(qv([0, 0]), qv([4, 0]), qv([1, 3]))}');
}
Output
centroid: [5/3, 1]
circumquadrancestaticmethod
static T? circumquadrance<T>(SymmetricForm<T> form, Vec<T> a, Vec<T> b, Vec<T> c)

The circumquadrance: the quadrance in form from the circumcentre to each vertex. Null when there is no circumcentre.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  print('3-4-5 right triangle: ${Centres.circumquadrance(blue, qv([0, 0]), qv([4, 0]), qv([0, 3]))}  (half the hypotenuse, squared)');
}
Output
3-4-5 right triangle: 25/4  (half the hypotenuse, squared)
final class Polyhedron<T>

A convex polyhedron given by vertices and the outward normals of its faces (a face is the set of vertices that maximise the dot product with its normal).

Quadrances and spreads use the Euclidean (blue) metric x^{2} + y^{2} + z^{2} and are exact elements of the field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final cube = Platonic.cube(Q);
  print('cube: ${cube.vertices.length} vertices, edge quadrance ${cube.edgeQuadrance}, ${cube.edges.length} edges');
}
Output
cube: 8 vertices, edge quadrance 4, 12 edges

Constructors

Polyhedronconstructor
Polyhedron(this.vertices, this.normals)

The polyhedron with vertices (3-vectors) and one outward face normal per face in normals; the faces are computed here. Throws RangeError if vertices is empty, and UnsupportedError if the field is not an OrderedField (finding the vertices of a face needs comparisons).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // An octahedron from its vertices and its face normals (integer lattice points).
  final p = Polyhedron(LatticePolyhedra.octahedron().map((v) => v.toVec()).toList(), LatticePolyhedra.cube().map((v) => v.toVec()).toList());
  print('octahedron edge quadrance ${p.edgeQuadrance}, dihedral spreads ${p.dihedralSpreads().toSet()}');
}
Output
octahedron edge quadrance 2, dihedral spreads {8/9}

Properties

final List<Vec<T>> vertices

The vertices, as given.

normalsfield
final List<Vec<T>> normals

The outward face normals, as given; face i has normal normals[i].

formfield
final SymmetricForm<T> form

The metric used for quadrances and spreads: the Euclidean form x^{2} + y^{2} + z^{2}.

facesfield
late final List<List<int>> faces

For each normal, the indices into vertices of the vertices on that face, in increasing order.

fieldgetter
ScalarField<T> get field

The field the coordinates live in.

late final T edgeQuadrance

The smallest quadrance between two distinct vertices (the edge quadrance of a regular solid); zero if there are fewer than two vertices or two vertices coincide.

edgesfield
late final List<(int, int)> edges

The edges: the index pairs (i, j), i < j, of vertices at exactly the edgeQuadrance. Right for regular and other equal-edged solids; a solid with edges of several lengths would need its edges listed another way.

int get eulerCharacteristic

V - E + F, the vertex count minus edges plus faces: 2 for every convex polyhedron, so it checks that the edges and faces were found correctly.

Methods

List<T> dihedralSpreads()

The spreads between the normals of faces sharing an edge (the dihedral spreads), one entry per such pair of faces; all equal for a regular solid. The spread between normals equals the spread of the dihedral angle.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  for (final (n, p) in [('tetrahedron', Platonic.tetrahedron(Q)), ('cube', Platonic.cube(Q)), ('octahedron', Platonic.octahedron(Q))]) {
    print('$n: ${p.dihedralSpreads().toSet()}');
  }
}
Output
tetrahedron: {8/9}
cube: {1}
octahedron: {8/9}
List<T> faceSpreads()

The spreads between the two edges at each corner of each face (the spreads of the face angles), one entry per corner: \frac{3}{4} for triangles, 1 for squares.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('tetrahedron: ${Platonic.tetrahedron(Q).faceSpreads().toSet()}  (equilateral faces: 3/4)');
  print('cube: ${Platonic.cube(Q).faceSpreads().toSet()}');
}
Output
tetrahedron: {3/4}  (equilateral faces: 3/4)
cube: {1}
abstract final class Platonic

The five Platonic solids with exact coordinates: the tetrahedron, cube and octahedron over any ordered field (such as Q), the icosahedron and dodecahedron over \mathbb{Q}(\sqrt{5}).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  for (final (name, p) in [('tetrahedron', Platonic.tetrahedron(Q)), ('cube', Platonic.cube(Q)), ('octahedron', Platonic.octahedron(Q))]) {
    print('$name: ${p.vertices.length} vertices, ${p.edges.length} edges, Euler ${p.eulerCharacteristic}, '
        'dihedral spread ${p.dihedralSpreads().toSet()}');
  }
}
Output
tetrahedron: 4 vertices, 6 edges, Euler 2, dihedral spread {8/9}
cube: 8 vertices, 12 edges, Euler 2, dihedral spread {1}
octahedron: 6 vertices, 12 edges, Euler 2, dihedral spread {8/9}

Static

tetrahedronstaticmethod
static Polyhedron<T> tetrahedron<T>(OrderedField<T> f)

The regular tetrahedron with vertices (1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1) over f. Edge quadrance 8, dihedral spread \frac{8}{9}, face spread \frac{3}{4}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final t = Platonic.tetrahedron(Q);
  print('vertices ${t.vertices}');
  print('dihedral spread ${t.dihedralSpreads().first}');
}
Output
vertices [[1, 1, 1], [1, -1, -1], [-1, 1, -1], [-1, -1, 1]]
dihedral spread 8/9
cubestaticmethod
static Polyhedron<T> cube<T>(OrderedField<T> f)

The cube with vertices (\pm1, \pm1, \pm1) over f. Edge quadrance 4; dihedral and face spreads 1.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final c = Platonic.cube(Q);
  print('${c.vertices.length} vertices, dihedral ${c.dihedralSpreads().toSet()}, faces ${c.faceSpreads().toSet()}');
}
Output
8 vertices, dihedral {1}, faces {1}
octahedronstaticmethod
static Polyhedron<T> octahedron<T>(OrderedField<T> f)

The octahedron with vertices (\pm1, 0, 0) and permutations over f. Edge quadrance 2, dihedral spread \frac{8}{9}, face spread \frac{3}{4}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final o = Platonic.octahedron(Q);
  print('${o.vertices.length} vertices, dihedral spread ${o.dihedralSpreads().toSet()}');
}
Output
6 vertices, dihedral spread {8/9}
icosahedronstaticmethod
static Polyhedron<Quad<T>> icosahedron<T>(OrderedField<Quad<T>> q5, Quad<T> phi)

The icosahedron with vertices the cyclic permutations of (0, \pm1, \pm\varphi), over q5 = \mathbb{Q}(\sqrt{5}), where phi is the golden ratio \varphi = \frac{1 + \sqrt{5}}{2} (from goldenRatio). Dihedral spread \frac{4}{9}, face spread \frac{3}{4}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Over ℚ(√5): the icosahedron's dihedral spread is exactly 4/9.
  final q5 = RealQuadraticField.of(5);
  final ico = Platonic.icosahedron(q5, goldenRatio(q5));
  print('${ico.vertices.length} vertices, dihedral spread ${ico.dihedralSpreads().map(q5.formatQuad).toSet()}');
}
Output
12 vertices, dihedral spread {4/9}
dodecahedronstaticmethod
static Polyhedron<Quad<T>> dodecahedron<T>(OrderedField<Quad<T>> q5, Quad<T> phi)

The dodecahedron with vertices (\pm1, \pm1, \pm1) and the cyclic permutations of (0, \pm\varphi, \pm\frac{1}{\varphi}), over q5 = \mathbb{Q}(\sqrt{5}), where phi is the golden ratio \varphi = \frac{1 + \sqrt{5}}{2} (from goldenRatio). Dihedral spread \frac{4}{5}, face spread \frac{5 + \sqrt{5}}{8}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q5 = RealQuadraticField.of(5);
  final d = Platonic.dodecahedron(q5, goldenRatio(q5));
  print('${d.vertices.length} vertices, dihedral spread ${d.dihedralSpreads().map(q5.formatQuad).toSet()}');
  print('face spread ${d.faceSpreads().map(q5.formatQuad).toSet()}');
}
Output
20 vertices, dihedral spread {4/5}
face spread {5/8 + 1/8√5}
final class Predicates<T>

Exact orientation, collinearity, in-circle and in-sphere tests over an OrderedField such as Q or a RealQuadraticField. Each answer is the exact sign of a determinant, so there are no wrong answers near degenerate configurations. Points are Vecs: 2-D for the planar tests, 3-D for the spatial ones.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  const p = Predicates(Q);
  print('orient2d (counter-clockwise):  ${p.orient2d(qv([0, 0]), qv([1, 0]), qv([0, 1]))}');
  print('orient2d (clockwise):          ${p.orient2d(qv([0, 0]), qv([0, 1]), qv([1, 0]))}');
  print('orient2d (collinear):          ${p.orient2d(qv([0, 0]), qv([1, 1]), qv([2, 2]))}');
  print('incircle (0,0) inside unit circle points: ${p.incircle(qv([1, 0]), qv([0, 1]), qv([-1, 0]), qv([0, 0]))}');
}
Output
orient2d (counter-clockwise):  1
orient2d (clockwise):          -1
orient2d (collinear):          0
incircle (0,0) inside unit circle points: 1

Constructors

Predicatesconstructor
const Predicates(this.field)

The predicates over field, such as Predicates(Q).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Exact predicates over any ordered field.
  final p = Predicates(Q);
  print('orient2d: ${p.orient2d(qv([0, 0]), qv([1, 0]), qv([0, 1]))}');
}
Output
orient2d: 1

Properties

fieldfield
final OrderedField<T> field

The ordered field the coordinates live in.

Methods

orient2dmethod
int orient2d(Vec<T> a, Vec<T> b, Vec<T> c)

The orientation of the 2-D points a, b, c: the sign of det[[bx - ax, by - ay], [cx - ax, cy - ay]], +1 when a \to b \to c turns counter-clockwise (left), -1 clockwise, 0 when the three points are collinear.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final p = Predicates(Q);
  final a = qv([0, 0]), b = qv([2, 1]);
  print('left turn ${p.orient2d(a, b, qv([0, 1]))}, right turn ${p.orient2d(a, b, qv([1, 0]))}, straight ${p.orient2d(a, b, qv([4, 2]))}');
  // A point a tiny rational distance off the line is still decided exactly.
  print('(4, 2 + 10⁻³⁰): ${p.orient2d(a, b, Vec(Q, [rat(4), rat(2) + Rational(BigInt.one, BigInt.from(10).pow(30))]))}');
}
Output
left turn 1, right turn -1, straight 0
(4, 2 + 10⁻³⁰): 1
collinearmethod
bool collinear(Vec<T> a, Vec<T> b, Vec<T> c)

Whether the 2-D points a, b, c lie on one line (also true when two of them coincide).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = Predicates(Q);
  print('${p.collinear(qv([0, 0]), qv(['1/3', '1/7']), qv([7, 3]))}, ${p.collinear(qv([0, 0]), qv(['1/3', '1/7']), qv([7, 4]))}');
}
Output
true, false
incirclemethod
int incircle(Vec<T> a, Vec<T> b, Vec<T> c, Vec<T> d)

The in-circle test: +1 when d is strictly inside the circle through a, b, c, -1 outside, 0 on it, for a, b, c in counter-clockwise order (orient2d(a, b, c) > 0). For clockwise a, b, c the sign is reversed; for collinear a, b, c (no circle) the result is the side of the line, not a circle test.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = Predicates(Q);
  final a = qv([1, 0]), b = qv([0, 1]), c = qv([-1, 0]);
  print('origin: ${p.incircle(a, b, c, qv([0, 0]))}, (0, −1): ${p.incircle(a, b, c, qv([0, -1]))}, (2, 2): ${p.incircle(a, b, c, qv([2, 2]))}');
  print('(3/5, −4/5), exactly on: ${p.incircle(a, b, c, qv(['3/5', '-4/5']))}');
}
Output
origin: 1, (0, −1): 0, (2, 2): -1
(3/5, −4/5), exactly on: 0
orient3dmethod
int orient3d(Vec<T> a, Vec<T> b, Vec<T> c, Vec<T> d)

The orientation of the 3-D points a, b, c, d: the sign of \det[b - a, c - a, d - a]. +1 when d is on the side of the plane abc that (b - a) \times (c - a) points to (so (0,0,0), (1,0,0), (0,1,0), (0,0,1) gives +1), -1 on the other side, 0 when the four points are coplanar.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = Predicates(Q);
  final a = qv([0, 0, 0]), b = qv([1, 0, 0]), c = qv([0, 1, 0]);
  print('above ${p.orient3d(a, b, c, qv([0, 0, 1]))}, below ${p.orient3d(a, b, c, qv([0, 0, -1]))}, in ${p.orient3d(a, b, c, qv([5, 7, 0]))}');
}
Output
above 1, below -1, in 0
coplanarmethod
bool coplanar(Vec<T> a, Vec<T> b, Vec<T> c, Vec<T> d)

Whether the 3-D points a, b, c, d lie in one plane.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = Predicates(Q);
  print('${p.coplanar(qv([1, 0, 0]), qv([0, 1, 0]), qv([0, 0, 1]), qv(['1/3', '1/3', '1/3']))}');
  print('${p.coplanar(qv([1, 0, 0]), qv([0, 1, 0]), qv([0, 0, 1]), qv([0, 0, 0]))}');
}
Output
true
false
inspheremethod
int insphere(Vec<T> a, Vec<T> b, Vec<T> c, Vec<T> d, Vec<T> e)

The in-sphere test: +1 when e is strictly inside the sphere through a, b, c, d, -1 outside, 0 on it, for positively oriented a, b, c, d (orient3d(a, b, c, d) > 0). For negative orientation the sign is reversed.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = Predicates(Q);
  final a = qv([1, 0, 0]), b = qv([0, 1, 0]), c = qv([0, 0, 1]), d = qv([-1, 0, 0]);
  final s = p.orient3d(a, b, c, d) > 0 ? [a, b, c, d] : [b, a, c, d];
  print('origin: ${p.insphere(s[0], s[1], s[2], s[3], qv([0, 0, 0]))}');
  print('(2, 0, 0): ${p.insphere(s[0], s[1], s[2], s[3], qv([2, 0, 0]))}');
  print('(0, 0, −1): ${p.insphere(s[0], s[1], s[2], s[3], qv([0, 0, -1]))}');
}
Output
origin: 1
(2, 0, 0): -1
(0, 0, −1): 0
abstract final class FloatPredicates

Robust predicates on doubles, with the same sign conventions as Predicates. Each test first evaluates the determinant in floating point and returns its sign when a static error bound certifies it; otherwise it redoes the test exactly over Q on the binary values of the inputs. The result is always the sign of the exact determinant of the given doubles, so a near-degenerate input never gets a wrong answer. Points are passed as coordinate lists (orient2d takes six separate coordinates).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Doubles in, an exact sign out: float with a certified error bound, exact fallback when too close.
  print('orient2d: ${FloatPredicates.orient2d(0, 0, 1, 1, 2, 2.0000000000000004)}');
}
Output
orient2d: 1

Static

exactFallbacksstaticfield
static int exactFallbacks

How many calls since program start (or the last reset) fell back to exact arithmetic, across all four tests. For benchmarks; assign 0 to reset.

orient2dstaticmethod
static int orient2d(double ax, double ay, double bx, double by, double cx, double cy)

The exact orientation of the points (ax, ay), (bx, by), (cx, cy): +1 counter-clockwise, -1 clockwise, 0 collinear, as Predicates.orient2d.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Three nearly collinear doubles: the plain float determinant says 0; the true sign is +1.
  const ax = 0.4999999999999978, ay = 0.4999999999999979, bx = 12.0, by = 12.0, cx = 24.0, cy = 24.0;
  final naive = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
  print('naive float determinant: $naive');
  print('FloatPredicates.orient2d: ${FloatPredicates.orient2d(ax, ay, bx, by, cx, cy)}');
  Vec<Rational> v(double x, double y) => Vec(Q, [Rational.fromDouble(x), Rational.fromDouble(y)]);
  print('exact over ℚ:            ${Predicates(Q).orient2d(v(ax, ay), v(bx, by), v(cx, cy))}');
}
Output
naive float determinant: 0.0
FloatPredicates.orient2d: 1
exact over ℚ:            1
incirclestaticmethod
static int incircle(List<double> a, List<double> b, List<double> c, List<double> d)

The exact in-circle test for 2-D points given as [x, y] lists: +1 when d is inside the circle through a, b, c (counter-clockwise), -1 outside, 0 on it, as Predicates.incircle.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The circle through (1,0), (0,1), (−1,0): +1 inside, 0 on, −1 outside.
  print('origin: ${FloatPredicates.incircle([1, 0], [0, 1], [-1, 0], [0, 0])}');
  print('(0, −1): ${FloatPredicates.incircle([1, 0], [0, 1], [-1, 0], [0, -1])}');
  print('(0.6, −0.8): ${FloatPredicates.incircle([1, 0], [0, 1], [-1, 0], [0.6, -0.8])}  (0.6 and 0.8 are not exact doubles)');
}
Output
origin: 1
(0, −1): 0
(0.6, −0.8): -1  (0.6 and 0.8 are not exact doubles)
orient3dstaticmethod
static int orient3d(List<double> a, List<double> b, List<double> c, List<double> d)

The exact orientation of 3-D points given as [x, y, z] lists: the sign of \det[b - a, c - a, d - a], the same convention as Predicates.orient3d.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A point 10⁻³⁰⁰ above the plane z = 0 is still decided correctly.
  print('just above: ${FloatPredicates.orient3d([0, 0, 0], [1, 0, 0], [0, 1, 0], [0.1, 0.2, 1e-300])}');
  print('in the plane: ${FloatPredicates.orient3d([0, 0, 0], [1, 0, 0], [0, 1, 0], [0.1, 0.2, 0])}');
}
Output
just above: 1
in the plane: 0
inspherestaticmethod
static int insphere(List<double> a, List<double> b, List<double> c, List<double> d, List<double> e)

The exact in-sphere test for 3-D points given as [x, y, z] lists, the same convention as

Float stage is a plain 4 \times 4 expansion with the conservative bound 10^{-12} · permanent, so near-degenerate inputs take the exact path more often than in the other tests.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = [1.0, 0.0, 0.0], b = [0.0, 1.0, 0.0], c = [0.0, 0.0, 1.0], d = [-1.0, 0.0, 0.0];
  // Orient the four points positively first (the convention of the test).
  final s = FloatPredicates.orient3d(a, b, c, d) > 0 ? [a, b, c, d] : [b, a, c, d];
  print('origin: ${FloatPredicates.insphere(s[0], s[1], s[2], s[3], [0, 0, 0])}');
  print('(0, −1, 0): ${FloatPredicates.insphere(s[0], s[1], s[2], s[3], [0, -1, 0])}');
  print('(3, 0, 0): ${FloatPredicates.insphere(s[0], s[1], s[2], s[3], [3, 0, 0])}');
}
Output
origin: 1
(0, −1, 0): 0
(3, 0, 0): -1
final class ProjectivePlane<T>

The projective plane over a field with an absolute (a symmetric form J on homogeneous coordinates).

Points and lines are both 3-vectors of homogeneous coordinates; proportional vectors are the same point or line. The quadrance between points and the spread between lines are projective (they do not depend on the scale of the coordinates) and are undefined for null points and lines, which lie on or touch the absolute.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Universal hyperbolic geometry: quadrance and spread from the projective plane, no distances.
  final h = ProjectivePlane.hyperbolic(Q);
  final a = h.point(rat(0), rat(0), rat(1)), b = h.point(rat(1), rat(0), rat(2)), c = h.point(rat(0), rat(1), rat(2));
  print('points a = $a, b = $b, c = $c (homogeneous)');
  print('q(a, b) = ${h.quadrance(a, b)}');
  print('q(a, c) = ${h.quadrance(a, c)}');
  print('S at a  = ${h.spread(h.join(a, b), h.join(a, c))}');
}
Output
points a = [0, 0, 1], b = [1, 0, 2], c = [0, 1, 2] (homogeneous)
q(a, b) = -1/3
q(a, c) = -1/3
S at a  = 1

Constructors

ProjectivePlaneconstructor
ProjectivePlane(Mat<T> j)

The plane with absolute J = j, a symmetric 3 \times 3 matrix (the size is not checked). Throws ArgumentError when j is not symmetric or \det J = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A projective plane from any symmetric 3 × 3 matrix J (the absolute conic xᵀJx = 0).
  final p = ProjectivePlane(Mat.diagonal(Q, [rat(1), rat(1), rat(-1)]));
  print('point form:\n${p.points.matrix}');
  print('q([0:0:1], [1:0:2]) = ${p.quadrance(p.pointOf(0, 0, 1), p.pointOf(1, 0, 2))}');
}
Output
point form:
1 0 0
0 1 0
0 0 -1
q([0:0:1], [1:0:2]) = -1/3
factory ProjectivePlane.hyperbolic(ScalarField<T> f)

Universal hyperbolic geometry: J = \operatorname{diag}(1, 1, -1), null circle x^{2} + y^{2} = z^{2}.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Universal hyperbolic geometry: the null circle x² + y² = z² plays the role of the boundary.
  final h = ProjectivePlane.hyperbolic(Q);
  print('[3:4:5] is null: ${h.isNullPoint(h.pointOf(3, 4, 5))}');
  print('q([0:0:1], [1:0:2]) = ${h.quadrance(h.pointOf(0, 0, 1), h.pointOf(1, 0, 2))}');
}
Output
[3:4:5] is null: true
q([0:0:1], [1:0:2]) = -1/3
factory ProjectivePlane.elliptic(ScalarField<T> f)

Elliptic geometry: J = I (the sphere with antipodes identified).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Elliptic geometry: J = I, points are lines through the origin of 3-space.
  final e = ProjectivePlane.elliptic(Q);
  print('q([1:0:0], [0:1:0]) = ${e.quadrance(e.pointOf(1, 0, 0), e.pointOf(0, 1, 0))}');
  print('q([1:0:0], [1:1:0]) = ${e.quadrance(e.pointOf(1, 0, 0), e.pointOf(1, 1, 0))}');
}
Output
q([1:0:0], [0:1:0]) = 1
q([1:0:0], [1:1:0]) = 1/2

Properties

pointsfield
final SymmetricForm<T> points

The form on points (J).

linesfield
final SymmetricForm<T> lines

The form on lines (adj J \propto J^{-1}).

fieldgetter
ScalarField<T> get field

The field the coordinates live in.

Methods

pointmethod
Vec<T> point(T x, T y, T z)

The point [x: y: z].

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final a = h.point(rat(1, 2), rat(1, 3), rat(1));
  print('a = $a; same point as [3:2:6]: ${a.isProportionalTo(h.pointOf(3, 2, 6))}');
}
Output
a = [1/2, 1/3, 1]; same point as [3:2:6]: true
pointOfmethod
Vec<T> pointOf(int x, int y, int z)

The point [x: y: z] from ints.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  print('${h.pointOf(1, 2, 5)}');
}
Output
[1, 2, 5]
joinmethod
Vec<T> join(Vec<T> a, Vec<T> b)

The line through the points a and b (their cross product). The zero vector when a and b are the same projective point.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final l = h.join(h.pointOf(0, 0, 1), h.pointOf(1, 1, 3));
  print('line through [0:0:1] and [1:1:3]: $l');
  print('[2:2:5] on it: ${h.incident(h.pointOf(2, 2, 5), l)}');
}
Output
line through [0:0:1] and [1:1:3]: [-1, 1, 0]
[2:2:5] on it: true
meetmethod
Vec<T> meet(Vec<T> l, Vec<T> m)

The point where the lines l and m meet (their cross product). The zero vector when they are the same line.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Two "parallel" affine lines still meet, at a point at infinity [x:y:0].
  final h = ProjectivePlane.hyperbolic(Q);
  final l = h.join(h.pointOf(0, 0, 1), h.pointOf(1, 2, 1)), m = h.join(h.pointOf(1, 0, 1), h.pointOf(2, 2, 1));
  print('meet: ${h.meet(l, m)}');
}
Output
meet: [2, 4, 0]
Vec<T> dualOfPoint(Vec<T> a)

The dual line a \perp = J a of a point (its polar with respect to the absolute).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The dual line a⊥ = J a (the polar of a with respect to the null circle).
  final h = ProjectivePlane.hyperbolic(Q);
  final a = h.pointOf(1, 0, 2);
  print('a⊥ = ${h.dualOfPoint(a)}; dual back: ${h.dualOfLine(h.dualOfPoint(a))}');
}
Output
a⊥ = [1, 0, -2]; dual back: [-1, 0, -2]
Vec<T> dualOfLine(Vec<T> l)

The dual point L \perp = \operatorname{adj}(J) L of a line (its pole).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final l = h.join(h.pointOf(0, 0, 1), h.pointOf(1, 0, 2));
  print('pole of $l: ${h.dualOfLine(l)}');
}
Output
pole of [0, 1, 0]: [0, -1, 0]
bool isNullPoint(Vec<T> a)

Whether a lies on the absolute (a null point): a^{T} J a = 0. Quadrances from a null point are undefined.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  for (final p in [h.pointOf(3, 4, 5), h.pointOf(0, 0, 1), h.pointOf(5, 12, 13)]) print('$p null: ${h.isNullPoint(p)}');
}
Output
[3, 4, 5] null: true
[0, 0, 1] null: false
[5, 12, 13] null: true
bool isNullLine(Vec<T> l)

Whether l is tangent to the absolute (a null line): L^{T} \operatorname{adj}(J) L = 0. Spreads with a null line are undefined.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The line x = z is tangent to the null circle x² + y² = z² at [1:0:1].
  final h = ProjectivePlane.hyperbolic(Q);
  print('⟨1:0:−1⟩ null: ${h.isNullLine(qv([1, 0, -1]))}, ⟨1:0:−2⟩ null: ${h.isNullLine(qv([1, 0, -2]))}');
}
Output
⟨1:0:−1⟩ null: true, ⟨1:0:−2⟩ null: false
incidentmethod
bool incident(Vec<T> a, Vec<T> l)

Whether the point a lies on the line l: a \cdot L = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final l = qv([1, -1, 0]); // x = y
  print('[2:2:7] on x = y: ${h.incident(h.pointOf(2, 2, 7), l)}, [1:2:3]: ${h.incident(h.pointOf(1, 2, 3), l)}');
}
Output
[2:2:7] on x = y: true, [1:2:3]: false
collinearmethod
bool collinear(Vec<T> a, Vec<T> b, Vec<T> c)

Whether the three points lie on one line: \det[a b c] = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  print('${h.collinear(h.pointOf(0, 0, 1), h.pointOf(1, 1, 2), h.pointOf(2, 2, 3))}, ${h.collinear(h.pointOf(0, 0, 1), h.pointOf(1, 1, 2), h.pointOf(2, 1, 3))}');
}
Output
true, false
bool concurrent(Vec<T> l, Vec<T> m, Vec<T> n)

Whether the three lines pass through one point: \det[l m n] = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  // Three lines through [0:0:1].
  print('${h.concurrent(qv([1, 0, 0]), qv([0, 1, 0]), qv([1, 1, 0]))}, ${h.concurrent(qv([1, 0, 0]), qv([0, 1, 0]), qv([1, 1, 1]))}');
}
Output
true, false
bool perpendicularPoints(Vec<T> a, Vec<T> b)

Whether the points a and b are perpendicular: b lies on the dual line a⊥, i.e. a^{T} J b = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final a = h.pointOf(1, 0, 2), b = h.pointOf(2, 3, 1);
  print('a ⊥ b: ${h.perpendicularPoints(a, b)}  (b lies on a⊥ = ${h.dualOfPoint(a)})');
  print('quadrance of perpendicular points: ${h.quadrance(a, b)}');
}
Output
a ⊥ b: true  (b lies on a⊥ = [1, 0, -2])
quadrance of perpendicular points: 1
bool perpendicularLines(Vec<T> l, Vec<T> m)

Whether the lines l and m are perpendicular: M passes through the dual point L⊥.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final l = qv([1, 0, 0]), m = qv([0, 1, 0]);
  print('x = 0 ⊥ y = 0: ${h.perpendicularLines(l, m)}, spread ${h.spread(l, m)}');
}
Output
x = 0 ⊥ y = 0: true, spread 1
quadrancemethod
T quadrance(Vec<T> a, Vec<T> b)

The projective quadrance q(a, b) = 1 - \frac{(a^{T}Jb)^{2}}{(a^{T}Ja)(b^{T}Jb)}; zero for equal points, one for perpendicular. It need not lie between 0 and 1: in the hyperbolic plane, [1: 0: 2] and [0: 0: 1] have \operatorname{quadrance} - \frac{1}{3}. Throws StateError when a or b is a null point.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Inside the null circle quadrances are negative, and they grow in size without bound toward it.
  final h = ProjectivePlane.hyperbolic(Q);
  final o = h.pointOf(0, 0, 1);
  for (final x in [1, 2, 3, 9]) print('q(O, [$x:0:${x + 1}]) = ${h.quadrance(o, h.pointOf(x, 0, x + 1))}');
}
Output
q(O, [1:0:2]) = -1/3
q(O, [2:0:3]) = -4/5
q(O, [3:0:4]) = -9/7
q(O, [9:0:10]) = -81/19
spreadmethod
T spread(Vec<T> l, Vec<T> m)

The projective spread S(L, M) = 1 - \frac{(L^{T} \operatorname{adj}(J) M)^{2}}{(L^{T} \operatorname{adj}(J) L)(M^{T} \operatorname{adj}(J) M)}, the dual of quadrance: zero for equal lines, one for perpendicular. Throws StateError when l or m is a null line.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final o = h.pointOf(0, 0, 1);
  final l = h.join(o, h.pointOf(1, 0, 2)), m = h.join(o, h.pointOf(1, 1, 3));
  print('S = ${h.spread(l, m)}  (at the centre it agrees with the Euclidean spread 1/2)');
}
Output
S = 1/2  (at the centre it agrees with the Euclidean spread 1/2)
altitudemethod
Vec<T> altitude(Vec<T> a, Vec<T> l)

The altitude from a to l: the line through a and the pole of l (perpendicular to l).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final a = h.pointOf(1, 1, 4), l = h.join(h.pointOf(0, 0, 1), h.pointOf(1, 0, 2));
  final alt = h.altitude(a, l);
  print('altitude: $alt, through a: ${h.incident(a, alt)}, ⊥ l: ${h.perpendicularLines(alt, l)}');
}
Output
altitude: [4, 0, -1], through a: true, ⊥ l: true
Vec<T> orthocentre(Vec<T> a1, Vec<T> a2, Vec<T> a3)

The orthocentre of the triangle a_{1}a_{2}a_{3} (the altitudes are concurrent in universal geometry too).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final a1 = h.pointOf(0, 0, 1), a2 = h.pointOf(1, 0, 3), a3 = h.pointOf(0, 1, 2);
  final o = h.orthocentre(a1, a2, a3);
  print('hyperbolic orthocentre: $o');
  print('third altitude passes through it: ${h.incident(o, h.altitude(a3, h.join(a1, a2)))}');
}
Output
hyperbolic orthocentre: [0, 0, -6]
third altitude passes through it: true
trianglemethod
ProjectiveTriangle<T> triangle(Vec<T> a1, Vec<T> a2, Vec<T> a3)

The triangle with vertices a1, a2, a3, with its quadrances (q_{i} opposite a_{i}) and spreads (S_{i} at a_{i}).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final t = h.triangle(h.pointOf(0, 0, 1), h.pointOf(1, 0, 3), h.pointOf(0, 1, 2));
  print('q = ${t.q1}, ${t.q2}, ${t.q3}');
  print('S = ${t.s1}, ${t.s2}, ${t.s3}');
}
Output
q = -1/2, -1/3, -1/8
S = 1, 2/3, 1/4
final class ProjectiveTriangle<T>

A triangle of the projective plane with its quadrances and spreads.

The sides, quadrances and spreads are computed on first use. Reading a quadrance or spread of a triangle with a null vertex or a null side throws StateError; check isNondegenerate first.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A hyperbolic triangle: its quadrances and spreads obey the projective laws, not the planar ones.
  final h = ProjectivePlane.hyperbolic(Q);
  final t = ProjectiveTriangle(h, h.pointOf(0, 0, 1), h.pointOf(1, 0, 2), h.pointOf(0, 1, 2));
  print('q = ${t.q1}, ${t.q2}, ${t.q3}; S = ${t.s1}, ${t.s2}, ${t.s3}');
  print('right angle at a1, Pythagoras q1 = q2 + q3 − q2q3: ${t.q1 == t.q2 + t.q3 - t.q2 * t.q3}');
}
Output
q = -7/9, -1/3, -1/3; S = 1, 3/7, 3/7
right angle at a1, Pythagoras q1 = q2 + q3 − q2q3: true

Constructors

ProjectiveTriangle(this.plane, this.a1, this.a2, this.a3)

The triangle a_{1}a_{2}a_{3} in plane. Nothing is checked here.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final e = ProjectivePlane.elliptic(Q);
  final t = ProjectiveTriangle(e, e.pointOf(1, 0, 0), e.pointOf(0, 1, 0), e.pointOf(1, 1, 1));
  print('elliptic q = ${t.q1}, ${t.q2}, ${t.q3}; nondegenerate ${t.isNondegenerate}');
}
Output
elliptic q = 2/3, 2/3, 1; nondegenerate true

Properties

planefield
final ProjectivePlane<T> plane

The plane, with its absolute, the triangle lives in.

a1field
final Vec<T> a1

The vertices a_{1}, a_{2}, a_{3}.

a2field
final Vec<T> a2

The vertices a_{1}, a_{2}, a_{3}.

a3field
final Vec<T> a3

The vertices a_{1}, a_{2}, a_{3}.

fgetter
ScalarField<T> get f

The field the coordinates live in.

l1field
late final Vec<T> l1

The sides as lines: l_{1} = a_{2}a_{3}, l_{2} = a_{1}a_{3}, l_{3} = a_{1}a_{2} (l_{i} opposite a_{i}).

l2field
late final Vec<T> l2

The sides as lines: l_{1} = a_{2}a_{3}, l_{2} = a_{1}a_{3}, l_{3} = a_{1}a_{2} (l_{i} opposite a_{i}).

l3field
late final Vec<T> l3

The sides as lines: l_{1} = a_{2}a_{3}, l_{2} = a_{1}a_{3}, l_{3} = a_{1}a_{2} (l_{i} opposite a_{i}).

q1field
late final T q1

The quadrances of the sides: q_{1} = q(a_{2}, a_{3}), q_{2} = q(a_{1}, a_{3}), q_{3} = q(a_{1}, a_{2}) (q_{i} opposite a_{i}).

q2field
late final T q2

The quadrances of the sides: q_{1} = q(a_{2}, a_{3}), q_{2} = q(a_{1}, a_{3}), q_{3} = q(a_{1}, a_{2}) (q_{i} opposite a_{i}).

q3field
late final T q3

The quadrances of the sides: q_{1} = q(a_{2}, a_{3}), q_{2} = q(a_{1}, a_{3}), q_{3} = q(a_{1}, a_{2}) (q_{i} opposite a_{i}).

s1field
late final T s1

The spreads at the vertices: s_{1} = S(l_{2}, l_{3}) at a_{1}, s_{2} = S(l_{1}, l_{3}) at a_{2}, s_{3} = S(l_{1}, l_{2}) at a_{3}.

s2field
late final T s2

The spreads at the vertices: s_{1} = S(l_{2}, l_{3}) at a_{1}, s_{2} = S(l_{1}, l_{3}) at a_{2}, s_{3} = S(l_{1}, l_{2}) at a_{3}.

s3field
late final T s3

The spreads at the vertices: s_{1} = S(l_{2}, l_{3}) at a_{1}, s_{2} = S(l_{1}, l_{3}) at a_{2}, s_{3} = S(l_{1}, l_{2}) at a_{3}.

bool get isNondegenerate

Whether the vertices are not collinear and no vertex or side is null, so every quadrance and spread is defined.

bool get satisfiesAllLaws

Whether every law in checks holds. Throws as checks.

Methods

checksmethod
Map<String, bool> checks()

The laws of universal geometry checked exactly on this triangle, by name: spreadLaw (as in the plane, via RtPlane.spreadLawHolds), crossLaw (the projective cross law with s_{3}), crossLaw1 (the same with s_{1}) and crossDualLaw (its dual, with q_{3}). All true for a non-degenerate triangle. Throws StateError when a vertex or side is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = ProjectivePlane.hyperbolic(Q);
  final t = h.triangle(h.pointOf(0, 0, 1), h.pointOf(1, 0, 3), h.pointOf(1, 2, 4));
  t.checks().forEach((law, ok) => print('$law: $ok'));
}
Output
spreadLaw: true
crossLaw: true
crossLaw1: true
crossDualLaw: true
final class FieldRatio<T> implements RatioBackend<T, Vec<T>>

A RatioBackend over a field and a metric: scalars are field elements, vectors are Vecs, and every operation is exact, so equality tests (isZero, same) need no tolerance.

Quadrance, spread, cross, twist and the rest are measured in the metric form; pass SymmetricForm.blue(Q) for ordinary Euclidean geometry over \mathbb{Q}, or a red, green or any other symmetric form for other geometries.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // A ratio backend over an exact field: the geometry API used by solvers, here blue 3-space.
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  final a = r.vector([1, 0, 0]), b = r.vector([1, 1, 0]);
  print('spread ${r.spread(a, b)}, cross ${r.cross(a, b)}, twist ${r.twist(a, b)}');
}
Output
spread 1/2, cross 1/2, twist 1

Constructors

FieldRatioconstructor
FieldRatio(this.form, {String? name})

The backend for the metric form. name overrides the default name (exact 2D over <field type>).

Throws ArgumentError unless form is two- or three-dimensional.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.red(Q), name: 'red');
  print('${r.quadrance(r.vector([3, 1]))}');
}
Output
8

Properties

formfield
final SymmetricForm<T> form

The metric B every measurement uses.

fgetter
ScalarField<T> get f

The field of form: where scalars and vector coordinates live.

namegetter
String get name

The name given to the constructor, or exact <n>D over <field type>.

dimensiongetter
int get dimension

The dimension of form: 2 or 3.

exactgetter
bool get exact

Always true: equality is exact.

Methods

fromIntmethod
T fromInt(int n)

The integer n as a field element.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${FieldRatio(SymmetricForm.blue(Q)).fromInt(4)}');
}
Output
4
addmethod
T add(T a, T b)

The field sum a + b.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.add(rat(1, 3), rat(1, 6))}');
}
Output
1/2
submethod
T sub(T a, T b)

The field difference a - b.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.sub(rat(1, 3), rat(1, 6))}');
}
Output
1/6
mulmethod
T mul(T a, T b)

The field product a \cdot b.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.mul(rat(2, 3), rat(9, 4))}');
}
Output
3/2
divmethod
T div(T a, T b)

The field quotient a / b; throws the field's division error when b = 0 (UnsupportedError over \mathbb{Q}).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.div(rat(2, 3), rat(4, 9))}');
}
Output
3/2
isZeromethod
bool isZero(T a, T scale)

Whether a is exactly zero; scale is ignored.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Exact fields ignore the scale argument (a float backend would use it as a tolerance).
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.isZero(rat(1, 3) - rat(1, 3), rat(1))}, ${r.isZero(rat(1, 1000000000), rat(1))}');
}
Output
true, false
toDoublemethod
double? toDouble(T a)

a as a double when the field is an OrderedField (\mathbb{Q}, \mathbb{Q}(\sqrt{d}) with d > 0, the real algebraic numbers); null otherwise (\mathbb{Z}/p and other fields with no order).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${FieldRatio(SymmetricForm.blue(Q)).toDouble(rat(1, 8))}');
}
Output
0.125
vectormethod
Vec<T> vector(List<int> coords)

The vector with integer coordinates coords.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${FieldRatio(SymmetricForm.blue(Q, 3)).vector([1, -2, 3])}');
}
Output
[1, -2, 3]
vaddmethod
Vec<T> vadd(Vec<T> a, Vec<T> b)

The vector sum a + b.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.vadd(r.vector([1, 2]), r.vector([3, 4]))}');
}
Output
[4, 6]
vsubmethod
Vec<T> vsub(Vec<T> a, Vec<T> b)

The vector difference a - b.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.vsub(r.vector([1, 2]), r.vector([3, 4]))}');
}
Output
[-2, -2]
vscalemethod
Vec<T> vscale(T k, Vec<T> v)

The scalar multiple k v.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.vscale(rat(1, 2), r.vector([3, 4]))}');
}
Output
[3/2, 2]
samemethod
bool same(Vec<T> a, Vec<T> b, T scale)

Whether a and b have exactly equal coordinates; scale is ignored.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.same(r.vector([1, 2]), qv([1, 2]), rat(1))}, ${r.same(r.vector([1, 2]), qv([1, 3]), rat(1))}');
}
Output
true, false
sizemethod
T size(Vec<T> v)

The Euclidean quadrance x^{2} + y^{2} (+ z^{2}) of the coordinates, whatever form is.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.red(Q));
  print('Euclidean size of (3, 4): ${r.size(r.vector([3, 4]))} (red quadrance ${r.quadrance(r.vector([3, 4]))})');
}
Output
Euclidean size of (3, 4): 25 (red quadrance -7)
dotmethod
T dot(Vec<T> a, Vec<T> b)

B(a, b) in form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.red(Q));
  print('red B((2,1), (1,3)) = ${r.dot(r.vector([2, 1]), r.vector([1, 3]))}');
}
Output
red B((2,1), (1,3)) = -1
quadrancemethod
T quadrance(Vec<T> a)

The quadrance Q(a) = B(a, a) in form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('${r.quadrance(r.vector([2, 3, 6]))}');
}
Output
49
spreadmethod
T spread(Vec<T> a, Vec<T> b)

The spread s(a, b) = 1 - \frac{B(a, b)^{2}}{Q(a)Q(b)} in form; throws StateError when a or b is null (Q = 0).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('${r.spread(r.vector([1, 0, 0]), r.vector([2, 3, 6]))}');
}
Output
45/49
crossmethod
T cross(Vec<T> a, Vec<T> b)

The cross c(a, b) = \frac{B(a, b)^{2}}{Q(a)Q(b)} = 1 - s in form; throws StateError when a or b is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('${r.cross(r.vector([1, 0, 0]), r.vector([2, 3, 6]))}');
}
Output
4/49
twistmethod
T twist(Vec<T> a, Vec<T> b)

The twist s / c (classically \tan^{2}\theta) in form; throws when a and b are perpendicular (c = 0) or either is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('${r.twist(r.vector([1, 0, 0]), r.vector([2, 3, 6]))}');
}
Output
45/4
T solidSpread(Vec<T> a, Vec<T> b, Vec<T> c)

The solid spread of the three edge vectors a, b, c at a vertex: \det \frac{G(a, b, c)}{Q(a)Q(b)Q(c)} in form. Throws UnsupportedError in two dimensions.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The solid spread of three directions: 1 for the axes, smaller for a narrow corner.
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('axes: ${r.solidSpread(r.vector([1, 0, 0]), r.vector([0, 1, 0]), r.vector([0, 0, 1]))}');
  print('tetrahedron corner: ${r.solidSpread(r.vector([1, 1, 0]), r.vector([1, 0, 1]), r.vector([0, 1, 1]))}');
}
Output
axes: 1
tetrahedron corner: 1/2
T dihedralSpread(Vec<T> common, Vec<T> a, Vec<T> b)

The dihedral spread between the planes span(common, a) and span(common, b) in form. Throws UnsupportedError in two dimensions.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('${r.dihedralSpread(r.vector([0, 0, 1]), r.vector([1, 0, 0]), r.vector([1, 1, 0]))}');
}
Output
1/2
T gramDeterminant(List<Vec<T>> vs)

The determinant of the Gram matrix B(v_{i}, v_{j}) of vs in form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  print('${r.gramDeterminant([r.vector([1, 0, 0]), r.vector([1, 2, 0]), r.vector([0, 1, 3])])}  (volume² 36)');
}
Output
36  (volume² 36)
reflectmethod
Vec<T> reflect(Vec<T> v, Vec<T> normal)

The reflection v - \frac{2B(v, n)}{Q(n)} n of v in the hyperplane B-perpendicular to normal; throws the field's division error when normal is null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r = FieldRatio(SymmetricForm.blue(Q));
  print('${r.reflect(r.vector([5, 0]), r.vector([1, 2]))}');
}
Output
[3, -4]
Vec<T> perpendicular(List<Vec<T>> vs)

A vector B-perpendicular to vs: in 2-D, to the single vector vs[0] (the quarter turn of M v, M the matrix of form); in 3-D, to vs[0] and vs[1] (the B-vector product). It is zero when the inputs are dependent.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final r3 = FieldRatio(SymmetricForm.blue(Q, 3)), r2 = FieldRatio(SymmetricForm.red(Q));
  print('3-D: ${r3.perpendicular([r3.vector([1, 0, 0]), r3.vector([0, 1, 0])])}');
  print('red 2-D: ${r2.perpendicular([r2.vector([2, 1])])}');
}
Output
3-D: [0, 0, 1]
red 2-D: [1, 2]
rotatemethod
Vec<T> rotate(List<T> k, Vec<T> v)

v under the Cayley rotation (B - K)^{-1}(B + K) of form. In 2-D, k is [t] and K = \begin{bmatrix}0 & t \\ -t & 0\end{bmatrix}; for the blue form, t = 1 sends (1, 0) to (0, -1), so positive t turns clockwise. In 3-D, k is the Gibbs vector (k_{0}, k_{1}, k_{2}) and K = kₓ. Throws ArgumentError when B - K is singular.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Rotate by the Cayley rotation of a rational skew vector: exact, stays rational.
  final r = FieldRatio(SymmetricForm.blue(Q, 3));
  final v = r.rotate([rat(0), rat(0), rat(1, 2)], r.vector([1, 0, 0]));
  print('$v, quadrance ${r.quadrance(v)}');
}
Output
[3/5, 4/5, 0], quadrance 1
final class Reflection<T>

The reflection in the hyperplane B-perpendicular to the non-null normal normal through the point through: x \mapsto x - \frac{2B(x - p, v)}{B(v, v)} \cdot v. An affine isometry of the metric, its own inverse, exact.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Reflect in the line through (0, 1) perpendicular to (1, 1).
  final r = Reflection(SymmetricForm.blue(Q), qv([1, 1]), qv([0, 1]));
  print('(0, 0) ↦ ${r.apply(qv([0, 0]))}, (0, 1) stays ${r.apply(qv([0, 1]))}');
}
Output
(0, 0) ↦ [1, 1], (0, 1) stays [0, 1]

Constructors

Reflectionconstructor
Reflection(this.form, this.normal, [Vec<T>? through])

The reflection of form in the hyperplane with normal normal through the point through (the origin when omitted). Throws ArgumentError when normal is null (B(v, v) = 0), since such a hyperplane has no reflection.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q), red = SymmetricForm.red(Q);
  final v = qv([1, 2]), p = qv([3, 1]);
  print('blue reflection of (3,1): ${Reflection(blue, v).apply(p)}');
  print('red reflection of (3,1):  ${Reflection(red, v).apply(p)}');
}
Output
blue reflection of (3,1): [1, -3]
red reflection of (3,1):  [11/3, 7/3]

Properties

formfield
final SymmetricForm<T> form

The metric the reflection preserves.

normalfield
final Vec<T> normal

The normal v of the hyperplane, a non-null vector.

throughfield
final Vec<T> through

A point p on the hyperplane; it and every other point of the hyperplane stay fixed.

motiongetter
RigidMotion<T> get motion

The same map as a RigidMotion of form: linear part L = I - 2 v (Mv)ᵀ/Q(v), translation p - L p. It is improper (\det L = -1).

Methods

applymethod
Vec<T> apply(Vec<T> x)

The image x - \frac{2B(x - p, v)}{B(v, v)} \cdot v of the point x, exactly. Applying it twice gives x back.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final blue = SymmetricForm.blue(Q);
  final r = Reflection(blue, qv([3, 4]));
  final x = qv([5, 0]);
  print('$x ↦ ${r.apply(x)}, quadrance kept: ${blue.norm(r.apply(x))}');
}
Output
[5, 0] ↦ [7/5, -24/5], quadrance kept: 25
extension ReflectionDecomposition<T> on SymmetricForm<T>

Cartan–Dieudonné, constructively: orthogonal bases, isometries and rigid motions as exact chains of reflections, edge pivots and face slides. The form must be non-degenerate (\det M \ne 0).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Cartan–Dieudonné, exactly: a rotation as two reflections.
  final blue = SymmetricForm.blue(Q);
  final rot = Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]);
  final ns = blue.reflectionNormals(rot);
  print('normals: $ns');
}
Output
normals: [[0, -2], [-2/5, 4/5]]

Methods

List<Vec<T>> orthogonalBasis()

A B-orthogonal basis of non-null vectors: dim vectors, pairwise perpendicular in this metric, none null. One exists for every non-degenerate form in characteristic ≠ 2; for the green form 2xy it is [1, 1], [\frac{1}{2}, -\frac{1}{2}]. Throws StateError for a degenerate form.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final f = SymmetricForm(Mat(Q, [[rat(0), rat(1)], [rat(1), rat(0)]]));
  final b = f.orthogonalBasis();
  print('green-orthogonal basis: $b, B = ${f.apply(b[0], b[1])}');
}
Output
green-orthogonal basis: [[1, 1], [1/2, -1/2]], B = 0
List<Vec<T>> reflectionNormals(Mat<T> a)

Linear reflections (hyperplanes through the origin) whose product, first applied first, is the isometry a (A^{T} M A = M). At most 2n reflections always; usually n or fewer (Cartan–Dieudonné's bound is n). The algorithm: for each vector x of an orthogonal basis in turn, the residual isometry R already fixes the earlier ones; if Rx - x is non-null reflect in it (one step, sends Rx to x), otherwise Rx + x is non-null, because Q(Rx - x) + Q(Rx + x) = 4Q(x) \ne 0, and reflecting in Rx + x then in x does it in two. Both normals are B-perpendicular to the earlier basis vectors, so those stay fixed. Pass each normal to Reflection (or reflectionMatrix) to rebuild a. Returns an empty list for the identity. Throws ArgumentError when a is not an isometry of this form, and StateError when the form is degenerate.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q, 3);
  // The rotation of the octahedron that cycles the axes.
  final cyc = Mat(Q, [[rat(0), rat(0), rat(1)], [rat(1), rat(0), rat(0)], [rat(0), rat(1), rat(0)]]);
  final ns = blue.reflectionNormals(cyc);
  print('reflection normals: $ns');
  var m = Mat.identity(Q, 3);
  for (final n in ns) m = blue.reflectionMatrix(n) * m;
  print('product equals the rotation: ${m == cyc}');
}
Output
reflection normals: [[0, -1, 1], [-1, 1, 0]]
product equals the rotation: true
List<Reflection<T>> decomposeMotion(RigidMotion<T> m)

A rigid motion x \mapsto Ax + t as exact affine reflections, applied in order. The linear part comes from reflectionNormals; a non-null translation t is two reflections in parallel hyperplanes (normal t, through the origin and through \frac{t}{2}); a null translation is split as k \cdot e + (t - k \cdot e) with both parts non-null. composeReflections of the result gives back m. m's linear part must be an isometry of this form (ArgumentError otherwise); throws StateError for a degenerate form or when no split of a null translation is found among k = 1, 2, 3.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final m = RigidMotion(blue, Mat(Q, [[rat(0), rat(-1)], [rat(1), rat(0)]]), qv([2, 0]));
  final rs = blue.decomposeMotion(m);
  print('${rs.length} reflections');
  final p = qv([1, 1]);
  var q = p;
  for (final r in rs) q = r.apply(q);
  print('applied in order: $q, the motion gives ${m.apply(p)}');
}
Output
4 reflections
applied in order: [1, 1], the motion gives [1, 1]
List<Reflection<T>>? pivotAboutEdge(Vec<T> p, Vec<T> d, Vec<T> from, Vec<T> to)

The pivot of a module about an edge: the rotation about the line through p with direction d (in 3-D) that turns the face normal from onto the face normal to, as two reflections in planes containing the edge: first in the plane with normal from, then in the plane with normal from + to \cdot \lambda. Exact exactly when Q(from)/Q(to) = \lambda^{2} for some \lambda in the field (an isometry preserves quadrance); null otherwise, or when from and to are not B-perpendicular to d, or when the faces are opposite (from = -\lambda \cdot to: a half turn needs another axis). The composite sends from to \lambda·to and fixes every point of the edge. d is only used for the perpendicularity check; from or to null also gives null.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Roll a cube about its bottom front edge: turn face normal (0,0,−1) onto (0,−1,0).
  final blue = SymmetricForm.blue(Q, 3);
  final rs = blue.pivotAboutEdge(qv([0, 0, 0]), qv([1, 0, 0]), qv([0, 0, -1]), qv([0, -1, 0]))!;
  var v = qv([0, 0, -1]);
  for (final r in rs) v = r.apply(v);
  print('${rs.length} reflections; (0,0,−1) ends at $v');
}
Output
2 reflections; (0,0,−1) ends at [0, -1, 0]
T? addRotationParameters(T t1, T t2)

The parameter of \operatorname{rotation}(t_{1}) \cdot \operatorname{rotation}(t_{2}) for a planar metric: \frac{t_{1} + t_{2}}{1 - t_{1}t_{2}/\det M} (the tangent addition law; derivation: with A = M^{-1}J, A^{2} = -\frac{I}{\det M}). Rational parameters compose rationally, so an exact move splits into exact unequal sub-moves: rotation(1) (a quarter turn in blue) = \operatorname{rotation}(\frac{1}{2}) \cdot \operatorname{rotation}(\frac{1}{3}). Null for a half turn (denominator 0), which has no finite Cayley parameter. Throws StateError unless the form is 2-D.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // Rational rotation parameters add by the tangent addition law.
  final blue = SymmetricForm.blue(Q);
  final t = blue.addRotationParameters(rat(1, 2), rat(1, 3))!;
  print('t = $t');
  print('rotation(1/2)·rotation(1/3) == rotation($t): ${blue.rotation(rat(1, 2))! * blue.rotation(rat(1, 3))! == blue.rotation(t)}');
}
Output
t = 1
rotation(1/2)·rotation(1/3) == rotation(1): true
slidemethod
List<Reflection<T>> slide(Vec<T> t)

A slide across a face by the translation t: two reflections in parallel planes with normal t, applied in order. A null t (B(t, t) = 0, t \ne 0) is split into two non-null parts, giving four reflections; t = 0 gives an empty list. Throws as decomposeMotion.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final rs = blue.slide(qv([3, 0]));
  var p = qv([1, 1]);
  for (final r in rs) p = r.apply(p);
  print('${rs.length} parallel reflections slide (1, 1) to $p');
}
Output
2 parallel reflections slide (1, 1) to [4, 1]
abstract final class DehnScreen

Dehn's invariant screen on exact spreads (standard mathematics, not Wildberger's). For a rational spread s (classically \sin^{2}\theta), \theta is a rational multiple of \pi exactly when s \in \{0, \frac{1}{4}, \frac{1}{2}, \frac{3}{4}, 1\} (Niven: \cos 2\theta = 1 - 2s is rational, and 2\cos 2\theta is then an algebraic integer, so an integer in [-2, 2]). Both functions are static; the class has no instances.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Niven: a rational spread is a rational multiple of π only for 0, 1/4, 1/2, 3/4, 1.
  for (final s in [rat(1, 4), rat(1, 3), rat(8, 9)]) print('spread $s: ${DehnScreen.isRationalMultipleOfPi(s)}');
}
Output
spread 1/4: true
spread 1/3: false
spread 8/9: false

Static

static bool isRationalMultipleOfPi(Rational spread)

Whether an angle with this rational spread is a rational multiple of \pi: true exactly for 0, \frac{1}{4}, \frac{1}{2}, \frac{3}{4} and 1 (0^{\circ}, 30^{\circ}, 45^{\circ}, 60^{\circ} and 90^{\circ}, and their supplements). For example \frac{1}{3} gives false.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  for (final s in [rat(0), rat(1, 2), rat(3, 4), rat(2, 3)]) print('$s → ${DehnScreen.isRationalMultipleOfPi(s)}');
}
Output
0 → true
1/2 → true
3/4 → true
2/3 → false
static bool allDihedralAnglesRationalInPi(Iterable<Rational> dihedralSpreads)

A polyhedron whose dihedral spreads are all rational and all in Niven's set has Dehn invariant 0 (each term \ell \otimes \theta vanishes in \mathbb{R} \otimes \mathbb{R}/\pi\mathbb{Q}). Returns true in that case; false means "some dihedral angle is an irrational multiple of \pi", which for a polyhedron with a single dihedral angle (the regular solids) proves D \ne 0, so it is not scissors-congruent to a cube (Dehn 1901; Sydler 1965 gives the converse: equal volume and Dehn invariant suffice). For mixed dihedral angles a false is only a screen: the irrational terms might cancel.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The cube's dihedral spreads are 1; the regular tetrahedron's are 8/9 (not a rational multiple of π).
  print('cube: ${DehnScreen.allDihedralAnglesRationalInPi([rat(1)])}');
  print('tetrahedron: ${DehnScreen.allDihedralAnglesRationalInPi([rat(8, 9)])}');
}
Output
cube: true
tetrahedron: false
final class RtQuaternion<T>

A quaternion w + \xi + yj + zk over any field, not necessarily of norm 1.

Any non-zero quaternion q gives the rotation v \mapsto q v \bar{q} / |q|^{2} (toRotationMatrix, rotate); q and \lambda q give the same rotation, so rational quaternions need no normalising square root. Arithmetic is exact in field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  // The rational quaternion 1 + i + j turns space with denominators 3, exactly.
  final q = RtQuaternion.ints(Q, 1, 1, 1, 0);
  final m = q.toRotationMatrix();
  print('rotation matrix:\n$m');
  var v = qv([1, 2, 2]);
  for (var i = 0; i < 50; i++) v = m.apply(v);
  print('quadrance of (1, 2, 2) after 50 turns: ${v.dot(v)}');
  print('q⁴ = ${q * q * q * q}, norm ${(q * q * q * q).norm}');
}
Output
rotation matrix:
1/3 2/3 2/3
2/3 1/3 -2/3
-2/3 2/3 -1/3
quadrance of (1, 2, 2) after 50 turns: 9
q⁴ = (-7, -4, -4, 0), norm 81

Constructors

RtQuaternionconstructor
RtQuaternion(this.field, this.w, this.x, this.y, this.z)

The quaternion w + xi + yj + zk over field.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q = RtQuaternion(Q, rat(1), rat(1, 2), rat(0), rat(0));
  print('q = $q, norm ${q.norm}');
  print('rotates (0, 1, 0) to ${q.rotate(qv([0, 1, 0]))}');
}
Output
q = (1, 1/2, 0, 0), norm 5/4
rotates (0, 1, 0) to [0, 3/5, 4/5]
factory RtQuaternion.ints(ScalarField<T> f, int w, int x, int y, int z)

The quaternion with integer coordinates w + \xi + yj + zk over f.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q = RtQuaternion.ints(Q, 1, 1, 1, 1);
  print('q = $q: rotates the axes cyclically');
  for (final v in [qv([1, 0, 0]), qv([0, 1, 0]), qv([0, 0, 1])]) print('$v ↦ ${q.rotate(v)}');
}
Output
q = (1, 1, 1, 1): rotates the axes cyclically
[1, 0, 0] ↦ [0, 1, 0]
[0, 1, 0] ↦ [0, 0, 1]
[0, 0, 1] ↦ [1, 0, 0]

Properties

fieldfield
final ScalarField<T> field

The field the coordinates live in.

wfield
final T w

The coordinates: w is the scalar part, (x, y, z) the vector part.

xfield
final T x

The coordinates: w is the scalar part, (x, y, z) the vector part.

yfield
final T y

The coordinates: w is the scalar part, (x, y, z) the vector part.

zfield
final T z

The coordinates: w is the scalar part, (x, y, z) the vector part.

conjugategetter
RtQuaternion<T> get conjugate

The conjugate \bar{q} = w - \xi - yj - zk; q q̄ = norm.

normgetter
T get norm

The norm |q|^{2} = w^{2} + x^{2} + y^{2} + z^{2} (the blue quadrance of q, exactly). It is multiplicative:

pq² =p²q².
inversegetter
RtQuaternion<T> get inverse

The inverse \bar{q} / |q|^{2}, so that q \cdot q^{-1} = 1 exactly. Throws the field's division error when norm is zero (UnsupportedError over \mathbb{Q}); over \mathbb{Z}/p a non-zero quaternion can have norm zero.

hashCodegetter
int get hashCode

Methods

Mat<T> toRotationMatrix()

The rotation v \mapsto q v \bar{q} / |q|^{2} as an exact 3 \times 3 matrix (Euler–Rodrigues). q and \lambda q give the same rotation. Its first column times |q|^{2} is pythagoreanQuadruple of q. Throws StateError when norm is zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
import 'raya:convert';

void main() {
  final q = RtQuaternion.ints(Q, 1, 2, 2, 0);
  final m = q.toRotationMatrix();
  print(m);
  print('det ${m.determinant}, isometry ${SymmetricForm.blue(Q, 3).isIsometry(m)}');
}
Output
1/9 8/9 4/9
8/9 1/9 -4/9
-4/9 4/9 -7/9
det 1, isometry true
rotatemethod
Vec<T> rotate(Vec<T> v)

The 3-vector v rotated by v \mapsto q v \bar{q} / |q|^{2}, exactly. Throws StateError when norm is zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q = RtQuaternion.ints(Q, 2, 0, 0, 1);
  print('(1, 0, 0) ↦ ${q.rotate(qv([1, 0, 0]))}');
  print('axis (0, 0, 1) fixed: ${q.rotate(qv([0, 0, 1]))}');
}
Output
(1, 0, 0) ↦ [3/5, 4/5, 0]
axis (0, 0, 1) fixed: [0, 0, 1]
toStringmethod
String toString()

(w, x, y, z), each coordinate formatted by the field.

Operators

operator *operator
RtQuaternion<T> operator *(RtQuaternion<T> o)

The Hamilton product this·o (i^{2} = j^{2} = k^{2} = ijk = -1). Not commutative: ij = k but ji = -k.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Quaternion products compose rotations; i·j = k but j·i = −k.
  final i = RtQuaternion.ints(Q, 0, 1, 0, 0), j = RtQuaternion.ints(Q, 0, 0, 1, 0);
  print('i·j = ${i * j}, j·i = ${j * i}');
  final a = RtQuaternion.ints(Q, 1, 1, 0, 0), b = RtQuaternion.ints(Q, 1, 0, 1, 0);
  print('rotate by b then a == rotate by a·b: ${a.rotate(b.rotate(qv([1, 2, 3]))) == (a * b).rotate(qv([1, 2, 3]))}');
}
Output
i·j = (0, 0, 0, 1), j·i = (0, 0, 0, -1)
rotate by b then a == rotate by a·b: true
operator +operator
RtQuaternion<T> operator +(RtQuaternion<T> o)

The coordinatewise sum this + o.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = RtQuaternion.ints(Q, 1, 2, 3, 4), b = RtQuaternion(Q, rat(1, 2), rat(0), rat(-3), rat(1));
  print('a + b = ${a + b}');
}
Output
a + b = (3/2, 2, 0, 5)
operator ==operator
bool operator ==(Object other)

Whether other is a quaternion over the same type with exactly equal coordinates (q and \lambda q are not equal, though they give the same rotation).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // q and 2q are different quaternions but the same rotation.
  final q = RtQuaternion.ints(Q, 1, 1, 0, 0), q2 = RtQuaternion.ints(Q, 2, 2, 0, 0);
  print('q == 2q: ${q == q2}, same rotation: ${q.toRotationMatrix() == q2.toRotationMatrix()}');
}
Output
q == 2q: false, same rotation: true
class

Hurwitz

final class Hurwitz

A Hurwitz integer: a quaternion whose four coordinates are all integers, or all halves of odd integers.

The Hurwitz integers form a ring with Euclidean division (divRem) and greatest common divisors (rightGcd); its 24 units (units) are the binary tetrahedral group. Values are stored doubled, (2w, 2x, 2y, 2z), so all arithmetic is on BigInt and exact.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Hurwitz integers: quaternions with all-integer or all-half-integer coordinates; Euclidean, so gcds exist.
  final a = Hurwitz(3, 1, 0, 0), b = Hurwitz.half(1, 1, 1, 1);
  print('a = $a (norm ${a.norm}), b = $b (norm ${b.norm})');
  print('a·b = ${a * b}, norm ${(a * b).norm} = ${a.norm} × ${b.norm}');
}
Output
a = (3, 1, 0, 0) (norm 10), b = (1/2, 1/2, 1/2, 1/2) (norm 1)
a·b = (1, 2, 1, 2), norm 10 = 10 × 1

Constructors

Hurwitz.doubledconstructor
Hurwitz.doubled(this.w2, this.x2, this.y2, this.z2)

The Hurwitz integer with doubled coordinates w2, x2, y2, z2, that is \frac{w_{2} + x_{2} i + y_{2} j + z_{2} k}{2}.

Throws ArgumentError unless all four have the same parity.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Stored doubled: (2w, 2x, 2y, 2z). (1+i+j+k)/2 is doubled (1, 1, 1, 1).
  final h = Hurwitz.doubled(BigInt.one, BigInt.one, BigInt.one, BigInt.one);
  print('$h, norm ${h.norm}');
}
Output
(1/2, 1/2, 1/2, 1/2), norm 1
Hurwitzfactory
factory Hurwitz(int w, int x, int y, int z)

The Lipschitz (all-integer) quaternion w + \xi + yj + zk.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = Hurwitz(1, 2, 3, 4);
  print('$h, norm ${h.norm} = 1 + 4 + 9 + 16');
}
Output
(1, 2, 3, 4), norm 30 = 1 + 4 + 9 + 16
factory Hurwitz.half(int w, int x, int y, int z)

The half-integer quaternion \frac{w + \xi + yj + zk}{2}. Throws ArgumentError unless w, x, y, z have the same parity; pass all odd values (all even ones give the integer quaternion they halve to).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final h = Hurwitz.half(1, -1, 3, 1);
  print('$h = ${h.toQuaternion()}, norm ${h.norm}');
}
Output
(1/2, -1/2, 3/2, 1/2) = (1/2, -1/2, 3/2, 1/2), norm 3

Static

onestaticfield
static final Hurwitz one

The multiplicative identity 1.

unitsstaticmethod
static List<Hurwitz> units()

The 24 units: \pm1, \pm i, \pm j, \pm k and \frac{\pm1 \pm i \pm j \pm k}{2} (the binary tetrahedral group 2T ≅ SL(2, 3)).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final u = Hurwitz.units();
  print('${u.length} units, all of norm 1: ${u.every((x) => x.norm == BigInt.one)}');
  print(u.take(10).join('  '));
}
Output
24 units, all of norm 1: true
(1, 0, 0, 0)  (-1, 0, 0, 0)  (0, 1, 0, 0)  (0, -1, 0, 0)  (0, 0, 1, 0)  (0, 0, -1, 0)  (0, 0, 0, 1)  (0, 0, 0, -1)  (1/2, 1/2, 1/2, 1/2)  (1/2, 1/2, 1/2, -1/2)
rightGcdstaticmethod
static Hurwitz rightGcd(Hurwitz a, Hurwitz b)

A right greatest common divisor g of a and b (a = x \cdot g and b = y \cdot g for Hurwitz integers x, y) by the Euclidean algorithm with divRem. It is unique up to a unit on the left; for example \gcd(5, 3 + i) is 1 + 2i, of norm 5. rightGcd(a, 0) is a.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Right gcd of 5 and 1 + 2i: a Hurwitz divisor of norm 5.
  final g = Hurwitz.rightGcd(Hurwitz(5, 0, 0, 0), Hurwitz(1, 2, 0, 0));
  print('gcd = $g, norm ${g.norm}');
}
Output
gcd = (1, 2, 0, 0), norm 5

Properties

w2field
final BigInt w2

The doubled coordinates 2w, 2x, 2y, 2z, all of the same parity.

x2field
final BigInt x2

The doubled coordinates 2w, 2x, 2y, 2z, all of the same parity.

y2field
final BigInt y2

The doubled coordinates 2w, 2x, 2y, 2z, all of the same parity.

z2field
final BigInt z2

The doubled coordinates 2w, 2x, 2y, 2z, all of the same parity.

normgetter
BigInt get norm

The norm w^{2} + x^{2} + y^{2} + z^{2} (an integer for every Hurwitz integer).

conjugategetter
Hurwitz get conjugate

The conjugate w - \xi - yj - zk; q q̄ = norm.

isZerogetter
bool get isZero

Whether this is 0.

isUnitgetter
bool get isUnit

Whether this is one of the 24 units (norm 1).

hashCodegetter
int get hashCode

Methods

RtQuaternion<Rational> toQuaternion()

The same quaternion as an RtQuaternion over Q.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final q = Hurwitz.half(1, 1, 1, 1).toQuaternion();
  print('as a rational quaternion: $q');
  print('(1, 0, 0) ↦ ${q.rotate(qv([1, 0, 0]))}');
}
Output
as a rational quaternion: (1/2, 1/2, 1/2, 1/2)
(1, 0, 0) ↦ [0, 1, 0]
divRemmethod
(Hurwitz, Hurwitz) divRem(Hurwitz o)

Right division with remainder: returns (q, r) with this = q·o + r and N(r) < N(o) (the Hurwitz order is Euclidean). q rounds \mathrm{this} \cdot \frac{\bar{o}}{N(o)} to the nearer of the nearest Lipschitz point and the nearest half-integer point. Throws UnsupportedError when o is zero.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // a = q·b + r with N(r) < N(b).
  final a = Hurwitz(7, 3, 1, 0), b = Hurwitz(2, 1, 0, 1);
  final (q, r) = a.divRem(b);
  print('q = $q, r = $r, N(r) = ${r.norm} < N(b) = ${b.norm}');
  print('q·b + r == a: ${q * b + r == a}');
}
Output
q = (3, 0, 1, -1), r = (0, -1, 0, 0), N(r) = 1 < N(b) = 6
q·b + r == a: true
toStringmethod
String toString()

(w, x, y, z) with rational coordinates, such as (1/2, 1/2, 1/2, 1/2).

Operators

operator *operator
Hurwitz operator *(Hurwitz o)

The Hamilton product this·o, again a Hurwitz integer. Not commutative.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final i = Hurwitz(0, 1, 0, 0), j = Hurwitz(0, 0, 1, 0);
  print('i·j = ${i * j}, j·i = ${j * i}');
}
Output
i·j = (0, 0, 0, 1), j·i = (0, 0, 0, -1)
operator +operator
Hurwitz operator +(Hurwitz o)

The sum this + o, again a Hurwitz integer.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Hurwitz(1, 0, 0, 0) + Hurwitz.half(1, 1, 1, 1)}');
}
Output
(3/2, 1/2, 1/2, 1/2)
operator -operator
Hurwitz operator -(Hurwitz o)

The difference this − o, again a Hurwitz integer.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  print('${Hurwitz(2, 1, 0, 0) - Hurwitz.half(1, 1, 1, 1)}');
}
Output
(3/2, 1/2, -1/2, -1/2)
operator ==operator
bool operator ==(Object other)

Whether other is the same Hurwitz integer (equal coordinates).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final w = Hurwitz.half(-1, 1, 1, 1);
  print('ω³ == 1 for ω = (−1 + i + j + k)/2: ${w * w * w == Hurwitz(1, 0, 0, 0)}');
}
Output
ω³ == 1 for ω = (−1 + i + j + k)/2: true
class AffineMap<T>

An affine map x \mapsto A x + t: first the linear part A (a square matrix), then the translation t.

Entries are exact elements of a ScalarField (over Q, exact rationals), so apply, compose and inverse never round: m^{-1}(m(p)) is exactly p, however long the chain. An affine map keeps lines and parallelism and the ratios of lengths along a line; it changes quadrances and spreads unless A is an isometry, in which case use RigidMotion. For perspective maps, where parallel lines may meet, use ProjectiveMap.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // x ↦ A x + t: shear by A, then shift by t. Every entry is an exact rational.
  final m = AffineMap(Mat(Q, [[rat(1), rat(1)], [rat(0), rat(1)]]), qv([2, 0]));
  final p = qv(['1/3', 1]);
  print('m(p)      = ${m.apply(p)}');
  print('m⁻¹(m(p)) = ${m.inverse.apply(m.apply(p))}');
  final id = m.compose(m.inverse);
  print('m ∘ m⁻¹: linear part\n${id.linear}\ntranslation ${id.translation}');
}
Output
m(p)      = [10/3, 1]
m⁻¹(m(p)) = [1/3, 1]
m ∘ m⁻¹: linear part
1 0
0 1
translation [0, 0]

Constructors

AffineMapconstructor
AffineMap(this.linear, this.translation)

The map x ↦ linear x + translation. Throws ArgumentError unless linear is square and translation has the same dimension.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final scale = AffineMap(Mat.diagonal(Q, [rat(1, 2), rat(1, 2)]), qv([1, 1]));
  print('(4, 2) ↦ ${scale.apply(qv([4, 2]))}');
}
Output
(4, 2) ↦ [3, 2]
factory AffineMap.identity(ScalarField<T> f, int n)

The identity map of n-space over the field f: A = I, t = 0.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final id = AffineMap.identity(Q, 2);
  print('(3, 7) ↦ ${id.apply(qv([3, 7]))}');
}
Output
(3, 7) ↦ [3, 7]
factory AffineMap.translation(Vec<T> t)

The pure shift x \mapsto x + t (A = I).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final t = AffineMap.translation(qv(['1/2', -1]));
  print('(0, 0) ↦ ${t.apply(qv([0, 0]))}, twice: ${t.compose(t).apply(qv([0, 0]))}');
}
Output
(0, 0) ↦ [1/2, -1], twice: [1, -2]

Properties

linearfield
final Mat<T> linear

The linear part A, an n \times n matrix.

final Vec<T> translation

The translation t, added after the linear part.

fieldgetter
ScalarField<T> get field

The field the entries live in.

dimgetter
int get dim

The dimension n of the space the map acts on.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = AffineMap.translation(qv([1, 2, 3]));
  print('dim ${m.dim}, linear part:\n${m.linear}');
  print('translation ${m.translation}');
}
Output
dim 3, linear part:
1 0 0
0 1 0
0 0 1
translation [1, 2, 3]
inversegetter
AffineMap<T> get inverse

The inverse map x \mapsto A^{-1} x - A^{-1} t, so that m.inverse.apply(m.apply(x)) is exactly x.

It exists exactly when A is invertible (det A \ne 0). When A is singular (the map flattens space onto a line or a plane), this throws UnsupportedError; check linear.determinant first if that can happen.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = AffineMap(Mat(Q, [[rat(2), rat(1)], [rat(1), rat(1)]]), qv([3, -1]));
  final back = m.inverse;
  print('inverse: x ↦ A⁻¹ x + ${back.translation}');
  print('m⁻¹(m((5, 7))) = ${back.apply(m.apply(qv([5, 7])))}');
  // A singular linear part (here a projection onto the x-axis) has no inverse.
  final flat = AffineMap(Mat.diagonal(Q, [rat(1), rat(0)]), qv([0, 0]));
  try {
    flat.inverse;
  } on UnsupportedError catch (e) {
    print('singular A: ${e.message}');
  }
}
Output
inverse: x ↦ A⁻¹ x + [-4, 5]
m⁻¹(m((5, 7))) = [5, 7]
singular A: singular matrix

Methods

applymethod
Vec<T> apply(Vec<T> x)

The image A x + t of the point x, exactly.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final rot = AffineMap(Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]), qv([1, 0]));
  for (final p in [qv([0, 0]), qv([5, 0]), qv([0, 5])]) print('$p ↦ ${rot.apply(p)}');
}
Output
[0, 0] ↦ [1, 0]
[5, 0] ↦ [4, 4]
[0, 5] ↦ [-3, 3]
composemethod
AffineMap<T> compose(AffineMap<T> other)

The composite this ∘ other: apply other first, then this map. Its linear part is A \cdot A' and its translation A t' + t. Composition is not commutative: a.compose(b) and b.compose(a) differ in general.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // this ∘ other: apply the other map first.
  final shift = AffineMap.translation(qv([1, 0]));
  final dbl = AffineMap(Mat.diagonal(Q, [rat(2), rat(2)]), qv([0, 0]));
  print('double then shift: ${shift.compose(dbl).apply(qv([1, 1]))}');
  print('shift then double: ${dbl.compose(shift).apply(qv([1, 1]))}');
}
Output
double then shift: [3, 2]
shift then double: [4, 2]
ProjectiveMap<T> toProjective()

The same map as a ProjectiveMap: the (n + 1) \times (n + 1) homogeneous matrix with A in the top left, t in the last column and (0, …, 0, 1) as the last row. Throws ArgumentError when A is singular, since a projective map must be invertible.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final m = AffineMap(Mat(Q, [[rat(1), rat(2)], [rat(0), rat(1)]]), qv([3, 4]));
  final p = m.toProjective();
  print('homogeneous matrix:\n${p.matrix}');
  print('same image: ${p.apply(qv([1, 1]))} = ${m.apply(qv([1, 1]))}');
}
Output
homogeneous matrix:
1 2 3
0 1 4
0 0 1
same image: [6, 5] = [6, 5]
final class RigidMotion<T> extends AffineMap<T>

A rigid motion: an isometry of a metric followed by a translation. It keeps every quadrance and spread of that metric exactly.

The metric is a SymmetricForm B: the blue (Euclidean) form, the red or green forms of chromogeometry, or any other. The linear part A must satisfy A^{T} B A = B, which the constructor checks exactly. Rotations and reflections are rigid motions of the blue form; for the red form they include the Lorentz boosts of rational relativity. Composition and inversion return rigid motions of the same form, still exact.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // An isometry of the blue plane: rotation by the 3-4-5 triple, then a shift.
  final m = RigidMotion(SymmetricForm.blue(Q), Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]), qv([1, 2]));
  final a = qv([0, 0]), b = qv([2, 1]);
  print('Q before ${SymmetricForm.blue(Q).quadrance(a, b)}, after ${SymmetricForm.blue(Q).quadrance(m.apply(a), m.apply(b))}');
  print('proper: ${m.isProper}');
}
Output
Q before 5, after 5
proper: true

Constructors

RigidMotionconstructor
RigidMotion(this.form, Mat<T> linear, Vec<T> translation)

The rigid motion x ↦ linear x + translation of form. Throws ArgumentError when linear is not an isometry of form (A^{T} B A \ne B), or when the dimensions do not match.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final flip = RigidMotion(blue, Mat.diagonal(Q, [rat(1), rat(-1)]), qv([0, 0]));
  print('reflection in the x-axis: proper ${flip.isProper}, (2, 3) ↦ ${flip.apply(qv([2, 3]))}');
  // A shear is affine but not rigid: the constructor checks Aᵀ B A = B.
  try {
    RigidMotion(blue, Mat(Q, [[rat(1), rat(1)], [rat(0), rat(1)]]), qv([0, 0]));
  } on ArgumentError catch (e) {
    print('shear: ${e.message}');
  }
}
Output
reflection in the x-axis: proper false, (2, 3) ↦ [2, -3]
shear: the linear part is not an isometry of the form

Properties

formfield
final SymmetricForm<T> form

The metric this motion preserves.

inversegetter
RigidMotion<T> get inverse

The inverse rigid motion, again a rigid motion of form. For a nondegenerate form (\det B \ne 0) it always exists, since then det A = \pm1; for a degenerate form a singular A throws UnsupportedError, as in AffineMap.inverse.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final m = RigidMotion(blue, Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]), qv([1, 2]));
  final back = m.inverse; // still a RigidMotion of the same form
  print('m⁻¹ is a rigid motion: ${back is RigidMotion<Rational>}');
  print('m⁻¹(m((7, -3))) = ${back.apply(m.apply(qv([7, -3])))}');
}
Output
m⁻¹ is a rigid motion: true
m⁻¹(m((7, -3))) = [7, -3]
isPropergetter
bool get isProper

Whether the motion is proper (det A = 1, like a rotation) rather than improper (det A = -1 for a nondegenerate form, like a reflection).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final turn = RigidMotion(blue, Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]), qv([0, 0]));
  final flip = RigidMotion(blue, Mat.diagonal(Q, [rat(1), rat(-1)]), qv([0, 0]));
  print('rotation: proper ${turn.isProper}, det ${turn.linear.determinant}');
  print('reflection: proper ${flip.isProper}, det ${flip.linear.determinant}');
  print('two reflections: proper ${flip.compose(flip).isProper}');
}
Output
rotation: proper true, det 1
reflection: proper false, det -1
two reflections: proper true

Methods

composemethod
RigidMotion<T> compose(AffineMap<T> other)

The composite this ∘ other (apply other first) as a rigid motion of the same form. Throws ArgumentError when other's linear part is not an isometry of form, since the composite would not be rigid.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final blue = SymmetricForm.blue(Q);
  final r = RigidMotion(blue, Mat(Q, [[rat(3, 5), rat(-4, 5)], [rat(4, 5), rat(3, 5)]]), qv([0, 0]));
  final r2 = r.compose(r);
  print('rotation twice: linear part\n${r2.linear}');
  print('still proper: ${r2.isProper}');
}
Output
rotation twice: linear part
-7/25 -24/25
24/25 -7/25
still proper: true
final class ProjectiveMap<T>

A projective map: an invertible (n + 1) \times (n + 1) matrix acting on homogeneous coordinates, defined up to scale.

A point x of n-space is the homogeneous vector [x: 1]; the image [y: w] is the point y / w, or a point at infinity when w = 0. Proportional matrices give the same map (sameAs). Projective maps send lines to lines but, unlike AffineMaps, may make parallel lines meet: they are the perspective maps of a camera or a homography between two planes. All of it is exact.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = ProjectiveMap(Mat(Q, [[rat(1), rat(0), rat(0)], [rat(0), rat(1), rat(0)], [rat(1), rat(0), rat(1)]]));
  print('(1, 1) ↦ ${p.apply(qv([1, 1]))}, (−1, 0) ↦ ${p.apply(qv([-1, 0]))} (sent to infinity)');
}
Output
(1, 1) ↦ [1/2, 1/2], (−1, 0) ↦ null (sent to infinity)

Constructors

ProjectiveMapconstructor
ProjectiveMap(this.matrix)

The map with homogeneous matrix matrix. Throws ArgumentError when matrix is singular.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = ProjectiveMap(Mat(Q, [[rat(2), rat(0), rat(0)], [rat(0), rat(2), rat(0)], [rat(0), rat(0), rat(1)]]));
  print('scaling by 2: (3, 4) ↦ ${p.apply(qv([3, 4]))}');
}
Output
scaling by 2: (3, 4) ↦ [6, 8]
factory ProjectiveMap.fromFourPoints(List<Vec<T>> from, List<Vec<T>> to)

The unique projective map of the plane sending the four points from to to (no three collinear, given as affine 2-D points).

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // The perspective map that sends the unit square onto a quadrilateral.
  final sq = [qv([0, 0]), qv([1, 0]), qv([1, 1]), qv([0, 1])];
  final quad = [qv([0, 0]), qv([4, 0]), qv([3, 2]), qv([1, 2])];
  final p = ProjectiveMap.fromFourPoints(sq, quad);
  for (final v in sq) print('$v ↦ ${p.apply(v)}');
  print('centre (1/2, 1/2) ↦ ${p.apply(qv(['1/2', '1/2']))}');
}
Output
[0, 0] ↦ [0, 0]
[1, 0] ↦ [4, 0]
[1, 1] ↦ [3, 2]
[0, 1] ↦ [1, 2]
centre (1/2, 1/2) ↦ [2, 4/3]

Properties

matrixfield
final Mat<T> matrix

The homogeneous matrix, any one of the proportional matrices that give this map.

fieldgetter
ScalarField<T> get field

The field the entries live in.

inversegetter
ProjectiveMap<T> get inverse

The inverse map. It always exists; it is computed as the adjugate matrix, which is \det \cdot M^{-1} and so the same projective map as M^{-1}, with no division.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = ProjectiveMap(Mat(Q, [[rat(2), rat(0), rat(1)], [rat(0), rat(1), rat(0)], [rat(1), rat(0), rat(1)]]));
  final x = qv([3, 4]);
  print('p(x)       = ${p.apply(x)}');
  print('p⁻¹(p(x))  = ${p.inverse.apply(p.apply(x)!)}');
  print('p ∘ p⁻¹ = id: ${p.compose(p.inverse).sameAs(ProjectiveMap(Mat.identity(Q, 3)))}');
}
Output
p(x)       = [7/4, 1]
p⁻¹(p(x))  = [3, 4]
p ∘ p⁻¹ = id: true

Methods

Vec<T> applyHomogeneous(Vec<T> x)

The image of the homogeneous point x (n + 1 coordinates), as a homogeneous point.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = ProjectiveMap(Mat(Q, [[rat(1), rat(0), rat(0)], [rat(0), rat(1), rat(0)], [rat(1), rat(0), rat(1)]]));
  print('[−1 : 0 : 1] ↦ ${p.applyHomogeneous(qv([-1, 0, 1]))}  (w = 0: a point at infinity)');
}
Output
[−1 : 0 : 1] ↦ [-1, 0, 0]  (w = 0: a point at infinity)
applymethod
Vec<T>? apply(Vec<T> x)

The image of the affine point x (n coordinates), or null when it is sent to infinity.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final p = ProjectiveMap(Mat(Q, [[rat(1), rat(0), rat(0)], [rat(0), rat(1), rat(0)], [rat(1), rat(0), rat(1)]]));
  print('(1, 2) ↦ ${p.apply(qv([1, 2]))}, (−1, 5) ↦ ${p.apply(qv([-1, 5]))}');
}
Output
(1, 2) ↦ [1/2, 1], (−1, 5) ↦ null
composemethod
ProjectiveMap<T> compose(ProjectiveMap<T> other)

The composite this ∘ other: apply other first, then this map.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  final a = ProjectiveMap(Mat(Q, [[rat(1), rat(0), rat(0)], [rat(0), rat(1), rat(0)], [rat(1), rat(0), rat(1)]]));
  final b = ProjectiveMap(Mat(Q, [[rat(1), rat(0), rat(0)], [rat(0), rat(1), rat(0)], [rat(-1), rat(0), rat(1)]]));
  print('a ∘ b is the identity: ${a.compose(b).sameAs(ProjectiveMap(Mat.identity(Q, 3)))}');
}
Output
a ∘ b is the identity: true
sameAsmethod
bool sameAs(ProjectiveMap<T> o)

Whether o is the same projective map: whether the two matrices are proportional. Use this rather than comparing matrix directly, since M and 7M are the same map.

Example
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';

void main() {
  // Proportional matrices are the same projective map.
  final a = ProjectiveMap(Mat.identity(Q, 3)), b = ProjectiveMap(Mat.identity(Q, 3).scale(rat(7)));
  print('I ~ 7I: ${a.sameAs(b)}, equal matrices: ${a.matrix == b.matrix}');
}
Output
I ~ 7I: true, equal matrices: false