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:
| Area | Types |
|---|---|
| Fields | Q (ordered \mathbb{Q}), OrderedAlgebraic, QuadraticExtension (\mathbb{Q}(\sqrt{d}), F_{p^{2}}), RealQuadraticField (exactly ordered) |
| Any metric, any dimension | Vec, Mat, SymmetricForm (quadrance, spread, cross, twist, reflections), Triangle (feeds RtPlane's laws and solvers) |
| More laws | quadruple quad formula, Ptolemy, Brahmagupta without roots, quadrilateral quadrea, projective laws |
| Plane, conics | Line (metric-general perpendiculars), Centres, Conic (rational parametrisation, tangents, polars) |
| Rotations, motions | Pythagorean triples and quadruples, spherePoint, RtQuaternion, Hurwitz, AffineMap, RigidMotion, ProjectiveMap, crossRatio |
| Universal geometry | ProjectivePlane (hyperbolic, elliptic), Chromogeometry, RedSpacetime |
| Robustness, boundary | Predicates, FloatPredicates (filtered + exact), FloatBoundary (bounded conversions, sensor input) |
| GPU tier, connectors | IVec3, IMat3, octahedralGroup, CubicLattice, FixedPointFormat, ExactLatticeState / RenderSnapshot / FeedbackGuard, ModuleKind, Module, Docking, Assembly |
| Polytopes | regularPolygon, Polyhedron, Platonic (\mathbb{Q} and \mathbb{Q}(\sqrt{5})) |
| Speed | FastTriangle (integer path) |
| Matrix trigonometry | Gram (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 |
| Reflections | Reflection, ReflectionDecomposition (Cartan–Dieudonné constructively, edge pivots and slides as exact reflection chains, rotation-parameter addition), DehnScreen |
| Ratio backends | FieldRatio: 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
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.
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)');
}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.
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']);
}
}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
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))}');
}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.
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]}');
}
}t = 1: [1, 1/2], 2xy = 1 t = 2: [2, 1/4], 2xy = 1 t = -1/4: [-1/4, -2], 2xy = 1
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.
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))}');
}p = 7: 3 p = 13: 2 p = 17: 3 p = 23: 5
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.
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)}');
}rat(3) = 3
rat(3, 4) = 3/4
rat("22/7") = 22/7
sum = 1/2Quad<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}).
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)}');
}φ = (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).
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)))}');
}|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.
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))}');
}collinear: 0 not: -65520
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.
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');
}Ptolemy residual for a cyclic quadrilateral: 0
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.
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})');
}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}.
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}');
}square: 16 2×3 rectangle: 576 = 16·36 = 576
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]).
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))}');
}u = [1, 2], v = [1/2, 3] u + v = [3/2, 5] u · v = 13/2 3u = [3, 6]
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].
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)');
}u = [3, 4], v = [9, 3] blue quadrance of u: 12 (25 mod 13) u·v = 0 (perpendicular)
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.
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])])}');
}det of (1,2), (3,4) = -2 det of the unit cube vectors = 1
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.
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)}');
}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.
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])}');
}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).
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}');
}linear part: 3/5 -4/5 4/5 3/5 proper: true
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.
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]))}');
}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.
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})');
}
}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).
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');
}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.
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}');
}(1)² + (2)² + (-2)² = (3)²: true
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.
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)}');
}point: [36/49, 24/49, -23/49] on the unit sphere: true
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).
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))}');
}cross ratio (0, 1; 2, 3) = 4/3 after x -> 2x + 1: 4/3
Constants and variables
const double unitRoundoff = 1.1102230246251565e-162^{-53} \approx 1.11 \times 10^{-16}, the unit roundoff of binary64: one correctly rounded operation has relative error at most this.
const OrderedRationals Q = OrderedRationals()\mathbb{Q} with its order, the default field of this package: exact rational arithmetic with exact signs.
Classes
Bounded
final class Bounded
A double with a proven bound: |\text{exact} - \text{value}| \le \text{error}.
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)}');
}value 0.3333333333333333, error ≤ 2.7755575615628914e-17, contains 0.3333333333333333: true
Constructors
const Bounded(this.value, this.error)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)}');
}true, false
Properties
Methods
bool contains(double x)Whether x lies in the interval [value − error, value + error], so it could be the exact value.
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)}');
}√2 ≈ 1.4142135623730951 ± 3.1401849173675503e-16; contains 1.4142135623730951: true
String toString()FloatBoundary
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).
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)}');
}distance of quadrance 25/9: 1.6666666666666667 ± 3.7007434154171886e-16
Static
static Bounded value(Rational r)The rational r as the nearest double, with error \le \tfrac{1}{2} ulp of the result.
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}');
}1/10 → 0.1, error ≤ 6.938893903907228e-18
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).
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}');
}√2 from Q = 2: 1.4142135623730951, error ≤ 3.1401849173675503e-16
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.
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}');
}angle 1.0471975511965976 ± 6.661338147750939e-16; π/3 = 1.0471975511965976
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.
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}');
}rapidity 0.6931471805599453 ± 8.376829723743609e-16
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.
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');
}[0.3333333333333333, 2.0, -0.1], per-coordinate error ≤ 2.220446049250313e-16
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.
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');
}[3.0, 1000000.0, 0.3333333432674408], error ≤ 9.934107508824397e-9
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.
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)}');
}0.1 is exactly 3602879701896397/36028797018963968
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).
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)}');
}π 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.
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})');
}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.
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}');
}q = (237/256, 49/128, 0, 0), error 0.01640625 its rotation is exact: det 1
Colour
enum Colour
The three colours of chromogeometry: blue (Euclidean, x^{2} + y^{2}), red (x^{2} - y^{2}) and green (2xy).
Values
Chromogeometry
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.
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}');
}blue 29, red 21, green 20 blue² = red² + green²: true
Constructors
Chromogeometry(this.field)The blue, red and green forms over field.
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)}');
}blue 5, red 3, green 4
Properties
final SymmetricForm<T> blueThe forms Q_{b} = x^{2} + y^{2}, Q_{r} = x^{2} - y^{2} and Q_{g} = 2xy.
final SymmetricForm<T> redThe forms Q_{b} = x^{2} + y^{2}, Q_{r} = x^{2} - y^{2} and Q_{g} = 2xy.
final SymmetricForm<T> greenThe forms Q_{b} = x^{2} + y^{2}, Q_{r} = x^{2} - y^{2} and Q_{g} = 2xy.
Methods
SymmetricForm<T> form(Colour c)The form of the colour c.
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}');
}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.
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}');
}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}.
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)}');
}[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).
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]))}');
}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.
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)}');
}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.
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)}');
}Colour.blue orthocentre: [1, 1] Colour.red orthocentre: [1, -1] Colour.green orthocentre: [3, 3]
RedSpacetime
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).
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))}');
}velocity of t = 1/2: 4/5 boost: 5/3 4/3 4/3 5/3
Constructors
RedSpacetime(this.field)Spacetime over field, with the red form as its metric.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final st = RedSpacetime(Q);
print('the red form:\n${st.form.matrix}');
}the red form: 1 0 0 -1
Properties
Methods
Vec<T> event(T t, T x)The event at time t and position x.
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)}');
}event (t, x) = [5, 3], interval from the origin: 16
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.
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)))}');
}(5, 3): 16 (2, 2): 0 (1, 3): -8
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).
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))}');
}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).
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)}');
}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}.
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)');
}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.
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)');
}1/2 ⊕ 1/2 = 4/5 9/10 ⊕ 9/10 = 180/181 v ⊕ 1 = 1 (light stays light)
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).
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)');
}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.
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)}');
}v = 3/5: γ² = 25/16 v = 1/2: γ² = 4/3 v = 99/100: γ² = 10000/199
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.
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]))}');
}circle: Conic(1, 0, 1, 0, 0, -25) contains (3, 4): true tangent at (3, 4): ⟨6 : 8 : -50⟩ second meet: [-3, 4]
Constructors
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).
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}');
}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).
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))}');
}
}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
Mat<T> get matrixThe 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 isDegenerateWhether the conic is degenerate (a pair of lines, a double line, a point or empty over the field): \det M = 0.
T get discriminantThe 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
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.
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)}');
}C[3, 4] = 0 C[0, 0] = -25 C[5, 5] = 25
bool contains(Vec<T> p)Whether the point p lies on the conic.
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']))}');
}(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.
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]))}');
}direction (1,0): 0, (1,1): 1
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.
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)');
}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.
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]))}');
}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.
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}');
}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]
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.
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]))}');
}tangent: ⟨4 : -1 : -4⟩, contains (1, 0): true
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).
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']))}');
}polar of (5, 0): ⟨5 : 0 : -1⟩ polar of (3/5, 4/5) (on the circle, so the tangent): ⟨3/5 : 4/5 : -1⟩
String toString()Conic(a, b, c, d, e, f) with the coefficients formatted by the field.
ModuleKind
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
rhombicDodecahedronA rhombic dodecahedron on the face-centred cubic lattice (the octet truss): 12 connectors, the permutations of (\pm1, \pm1, 0).
truncatedOctahedronA 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 connectorsThe connector points relative to the centre, in a fixed order (connector i is connectors[i]); a new list each call.
CubicLattice get latticeThe lattice the module centres occupy (in the doubled coordinates used here).
int get contactQuadranceThe 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 axisSpreadsThe 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.
Module
final class Module
A module placed at an integer centre with a lattice rotation.
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)}');
}12 connectors; connector 0 at (-1, -1, 0)
Constructors
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.
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)}');
}direction of connector 0: (0, -1, 0)
Properties
final IVec3 centreThe centre, in the doubled integer coordinates of ModuleKind.connectors.
Methods
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.
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)]}');
}[(-1, 0, 0), (0, -1, 0), (0, 0, -1), (0, 0, 1), (0, 1, 0), (1, 0, 0)]
IVec3 connectorPoint(int i)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final m = Module(ModuleKind.cube, IVec3(4, 0, 0));
print('${m.connectorPoint(0)}');
}(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.
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))}');
}along +z: 3, along (1,1,0): -1
Docking
abstract final class Docking
Docking and collision, all exact integer tests.
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)}');
}docked at (2, 0, 0), overlap: false
Static
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.
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)))}');
}true false
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.
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}');
}neighbour centre: (2, 2, 0)
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.
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)))}');
}true, false
Assembly
final class Assembly
A set of placed modules with exact consistency checks.
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()}');
}true, true, false modules: 2, mated pairs: [(0, 5, 1, 0)]
Properties
final List<Module> modulesThe placed modules in the order they were added. The list is mutable; adding to it directly skips the checks in add.
Methods
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.
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)))}');
}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.
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()}');
}[(0, 5, 1, 0), (0, 4, 2, 1)]
FastTriangle
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.
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}');
}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.
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}');
}s1 = 3364/3893; agrees with Triangle: true
Properties
final Rational q1The 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}.
final Rational q2The 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}.
final Rational q3The 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}.
final Rational s1The 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}.
final Rational s2The 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}.
final Rational s3The 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}.
final Rational quadreaThe 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.
FieldOps
extension FieldOps<T> on ScalarField<T>
Derived operations available on every ScalarField: inverse, square, integer powers, sums and printing.
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])}');
}3⁻¹ = 4, 4² = 5, 2¹⁰ = 1, sum 1..10 = 0
Methods
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.
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)');
}ℚ: (3/7)⁻¹ = 7/3 ℤ/13: 5⁻¹ = 8 (5 · 8 = 40 = 1 mod 13)
T square(T a)a^{2}, the element a times itself.
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)}');
}(2/3)² = 4/9, 9² in ℤ/7 = 4
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.
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)}');
}(1/2)^10 = 1/1024, (1/2)^-3 = 8 Fermat in ℤ/101: 7^100 = 1
T sum(Iterable<T> xs)The sum of xs, exactly; zero for an empty iterable.
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)])}');
}1/1 + … + 1/6 = 49/20
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).
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${Q.format(rat(-3, 4))}, ${PrimeField(7).format(10)}');
}-3/4, 10
OrderedField
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.
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))}');
}sign(−2/3) = -1, toDouble(1/3) = 0.3333333333333333
Methods
int sign(T a)The exact sign of a: -1 when a < 0, 0 when a = 0, +1 when a > 0.
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)))}');
}sign(7 − 5√2) = -1, sign(3 − 2√2) = 1
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.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final q5 = RealQuadraticField.of(5);
print('φ ≈ ${q5.toDouble(goldenRatio(q5))}');
}φ ≈ 1.618033988749895
OrderedOps
extension OrderedOps<T> on OrderedField<T>
Comparison on an OrderedField.
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))}');
}compare(1/3, 2/7) = 1
Methods
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)).
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)))}');
}compare(√2, 99/70) = -1 (99/70 is just above √2) compare(√2, 140/99) = 1
OrderedRationals
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.
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))}');
}ℚ: 5/6, sign -1
Constructors
const OrderedRationals()The ordered rationals; the same field as Q.
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)))}');
}1/3, same as Q: true
Properties
Rational get zeroRational get oneint get characteristicMethods
Rational fromInt(int n)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${Q.fromInt(-7)}');
}-7
Rational fromRational(Rational r)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${Q.fromRational(rat(5, 8))}');
}5/8
Rational add(Rational a, Rational b)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}');
}1/10 + 2/10 = 3/10; doubles: 0.30000000000000004
Rational sub(Rational a, Rational b)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}');
}3/10 − 1/10 = 1/5; doubles: 0.19999999999999998
Rational mul(Rational a, Rational b)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}');
}(1/10)·3 = 3/10; doubles: 0.30000000000000004
Rational div(Rational a, Rational b)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('1/3 ÷ 1/9 = ${Q.div(rat(1, 3), rat(1, 9))}');
}1/3 ÷ 1/9 = 3
Rational neg(Rational a)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${Q.neg(rat(2, 5))}');
}-2/5
bool isZero(Rational a)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}');
}1/3 − 1/3 is zero: true; doubles 0.1 + 0.2 − 0.3 = 5.551115123125783e-17
bool equals(Rational a, Rational b)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('2/4 = 1/2: ${Q.equals(rat(2, 4), rat(1, 2))}');
}2/4 = 1/2: true
Rational? sqrt(Rational a)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))}');
}√(9/16) = 3/4, √2 = null
int sign(Rational a)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))}');
}-1, 0, 1
double toDouble(Rational a)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('1/3 → ${Q.toDouble(rat(1, 3))}');
}1/3 → 0.3333333333333333
String toString()OrderedAlgebraic
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.
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)}');
}√2 ≈ 1.4142135623730951 (stored exactly as a root of x² − 2), (√2)² = 2
Constructors
const OrderedAlgebraic()The ordered real algebraic numbers.
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)}');
}√2 + √3 ≈ 3.1462643699419726, sign 1
Properties
AlgebraicNumber get zeroAlgebraicNumber get oneint get characteristicMethods
AlgebraicNumber fromInt(int n)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${const OrderedAlgebraic().fromInt(5)}');
}5
AlgebraicNumber fromRational(Rational r)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${const OrderedAlgebraic().fromRational(rat(-3, 4))}');
}-3/4
AlgebraicNumber add(AlgebraicNumber a, AlgebraicNumber b)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))!)}');
}√2 + √2 ≈ 2.8284271247461903, equals √8: true
AlgebraicNumber sub(AlgebraicNumber a, AlgebraicNumber b)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))}');
}√2 − √2 = 0, is zero: true
AlgebraicNumber mul(AlgebraicNumber a, AlgebraicNumber b)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))!)}');
}√2 · √3 = √6: true
AlgebraicNumber div(AlgebraicNumber a, AlgebraicNumber b)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)}');
}1/√2 ≈ 0.7071067811865476, squared 1/2
AlgebraicNumber neg(AlgebraicNumber a)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))!))}');
}sign of −√5: -1
bool isZero(AlgebraicNumber a)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)}');
}zero: true
bool equals(AlgebraicNumber a, AlgebraicNumber b)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))!))}');
}√(3 + 2√2) = 1 + √2: true
AlgebraicNumber? sqrt(AlgebraicNumber a)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))}');
}√5 ≈ 2.23606797749979, √(−1) = null
int sign(AlgebraicNumber a)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)}');
}sign(√2 + √3 − √10) = -1
double toDouble(AlgebraicNumber a)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
const f = OrderedAlgebraic();
print('√7 ≈ ${f.toDouble(f.sqrt(f.fromInt(7))!)}');
}√7 ≈ 2.6457513110645907
String toString()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).
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))}');
}x = 1 + 1√2, x² = 3 + 2√2
Constructors
const Quad(this.a, this.b)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)');
}2 + 1√3, norm 1 (a unit: 2² − 3·1² = 1)
Properties
int get hashCodeMethods
String toString()Operators
bool operator ==(Object other)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))}');
}(1 + √2)(1 − √2) == −1: true
QuadraticExtension
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.
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))))}');
}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).
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)))}');
}x = 2 + 5√3, x⁻¹ = 5 + 5√3, x·x⁻¹ = 1
Properties
Quad<T> get zeroQuad<T> get oneint get characteristicMethods
Quad<T> of(T x)The base-field element x as the element x + 0\sqrt{d}.
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)))}');
}3/4 in ℚ(√2): 3/4
Quad<T> make(T x, T y)The element x + y√d.
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))}');
}φ = 1/2 + 1/2√5, φ² − φ − 1 = 0
Quad<T> conjugate(Quad<T> x)The conjugate a - b\sqrt{d}.
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)))}');
}conj(3 + 2√2) = 3 + -2√2, product 1
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.
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)))}');
}N(3 + 2√2) = 1, N(1 + √2) = -1
Quad<T> add(Quad<T> x, Quad<T> y)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))))}');
}3/2 + -2√2
Quad<T> sub(Quad<T> x, Quad<T> y)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))))}');
}0
Quad<T> mul(Quad<T> x, Quad<T> y)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)}');
}
}(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
Quad<T> neg(Quad<T> x)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))))}');
}-1 + 1√2
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.
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))))}');
}1/(1 + √2) = -1 + 1√2
bool isZero(Quad<T> x)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))}');
}x·x⁻¹ − 1 is zero: true
bool equals(Quad<T> a, Quad<T> b)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)))}');
}(1 + √2)² = 3 + 2√2: true
Quad<T> fromInt(int n)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final q2 = RealQuadraticField.of(2);
print('${q2.formatQuad(q2.fromInt(7))}');
}7
Quad<T> fromRational(Rational r)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final q2 = RealQuadraticField.of(2);
print('${q2.formatQuad(q2.fromRational(rat(2, 3)))}');
}2/3
Quad<T> div(Quad<T> a, Quad<T> b)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))))}');
}(3 + 2√2)/(1 + √2) = 1 + 1√2
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.
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!);
}√(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.
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));
}1/2 + 1/2√5 3 1√5 -1 + -2√5
String toString()RealQuadraticField
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.
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)}');
}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.
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))}');
}ℚ(√(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.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final q7 = RealQuadraticField.of(7);
print('${q7}, √7 ≈ ${q7.toDouble(q7.root)}');
}ℚ(√7), √7 ≈ 2.6457513110645907
Methods
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.
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)))}');
}sign(99 − 70√2) = 1
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.
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}');
}99 − 70√2 ≈ 0.005050633883346584 naive doubles: 0.005050633883342925
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).
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}');
}a·b = 0, a × b = (6, 3, -6), Q(a) = 9
Constructors
const IVec3(this.x, this.y, this.z)import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${const IVec3(3, 4, 12)}, quadrance ${const IVec3(3, 4, 12).quadrance}');
}(3, 4, 12), quadrance 169
Properties
int get quadrancex^{2} + y^{2} + z^{2}, exact (|coordinates| < 2^{31} keeps it below 2^{63}).
int get hashCodeMethods
int dot(IVec3 o)The dot product x \cdot x' + y \cdot y' + z \cdot z' with o.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${IVec3(1, 1, 0).dot(IVec3(1, -1, 5))}');
}0
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.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('x × y = ${IVec3(1, 0, 0).cross(IVec3(0, 1, 0))}');
}x × y = (0, 0, 1)
int quadranceTo(IVec3 o)The quadrance between this point and o, exact.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${IVec3(1, 1, 1).quadranceTo(IVec3(-1, -1, -1))}');
}12
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.
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)}');
}spread to (1, 0, 1): 3/4 spread to (0, 0, 2): 1 spread to (1, -1, 0): 1
Vec<Rational> toVec()The same vector as a 3-vector over Q, for use with the general field-based geometry.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${IVec3(1, -2, 3).toVec()}');
}[1, -2, 3]
Operators
IVec3 operator +(IVec3 o)The sum, coordinate by coordinate.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${IVec3(1, 2, 3) + IVec3(1, 1, 1)}');
}(2, 3, 4)
IVec3 operator -(IVec3 o)The difference, coordinate by coordinate.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${IVec3(1, 2, 3) - IVec3(1, 1, 1)}');
}(0, 1, 2)
IVec3 operator -()The opposite vector (-x, -y, -z).
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${-IVec3(1, -2, 3)}');
}(-1, 2, -3)
IVec3 operator *(int k)The vector scaled by the integer k.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${IVec3(1, 2, 3) * 4}');
}(4, 8, 12)
bool operator ==(Object other)Equal when all three coordinates are equal.
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)}');
}true, false
IMat3
final class IMat3
A 3 \times 3 integer matrix (a lattice symmetry), row-major.
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}');
}(1, 0, 0) ↦ (0, 1, 0), r⁴ = I: true
Constructors
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.
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}');
}orthogonal true, det 1
Static
static const IMat3 identity = IMat3([1, 0, 0, 0, 1, 0, 0, 0, 1])The identity matrix I.
Properties
int get determinantThe determinant \det M: +1 for a rotation in octahedralGroup, -1 for a reflection.
bool get isOrthogonalWhether 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.
int get hashCodeMethods
IVec3 apply(IVec3 v)The image M v of v, exactly.
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))}');
}(2, 1, 3)
Operators
IMat3 operator *(IMat3 o)The matrix product M·o: applying the result means applying o first, then this matrix.
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}');
}ab == ba: false
bool operator ==(Object other)Equal when all 9 entries are equal.
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])}');
}r² == half turn: true
CubicLattice
enum CubicLattice
The cubic lattices and their nearest-neighbour shells, in integer coordinates.
Values
bodyCentredPoints with all coordinates even or all odd: 8 neighbours (\pm1, \pm1, \pm1) at quadrance 3.
faceCentredPoints 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 neighbourQuadranceThe nearest-neighbour quadrance: 1, 3 or 2 for simple, body-centred and face-centred.
List<IVec3> get neighboursThe nearest-neighbour directions (the struts of the lattice truss): 6, 8 or 12 vectors, a new list each call.
Methods
bool contains(IVec3 p)Whether the integer point p belongs to this lattice.
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)}');
}CubicLattice.simple contains (1, 1, 0): true CubicLattice.bodyCentred contains (1, 1, 0): false CubicLattice.faceCentred contains (1, 1, 0): true
LatticePolyhedra
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.
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');
}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.
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)');
}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).
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(', ')}');
}12 face normals, e.g. (-1, -1, 0), (-1, 0, -1), (-1, 0, 1), (-1, 1, 0)
static List<IVec3> cuboctahedron()The cuboctahedron (the FCC nearest-neighbour shell): its 12 vertices are the permutations of (\pm1, \pm1, 0).
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()}');
}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).
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()}');
}24 vertices, quadrance {5}static List<IVec3> cube()The cube: the 8 vertices (\pm1, \pm1, \pm1).
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${LatticePolyhedra.cube()}');
}[(-1, -1, -1), (-1, -1, 1), (-1, 1, -1), (-1, 1, 1), (1, -1, -1), (1, -1, 1), (1, 1, -1), (1, 1, 1)]
static List<IVec3> octahedron()The octahedron: the 6 vertices (\pm1, 0, 0) and permutations.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${LatticePolyhedra.octahedron()}');
}[(-1, 0, 0), (0, -1, 0), (0, 0, -1), (0, 0, 1), (0, 1, 0), (1, 0, 0)]
static List<IVec3> tetrahedron()The regular tetrahedron inscribed in the cube: (1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1).
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])}}');
}[(1, 1, 1), (1, -1, -1), (-1, 1, -1), (-1, -1, 1)], edge quadrances {8}FixedPointFormat
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}. |
|---|
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))}');
}stored 384 means 3/2; 3/16 is stored as 48
Constructors
const FixedPointFormat(this.fractionBits)The format with k = fractionBits fractional bits. Use 0 \le k \le 62; the range is not checked.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
const fmt = FixedPointFormat(4);
print('scale ${fmt.scale}, one unit = ${fmt.decode(1)}');
}scale 16, one unit = 1/16
Static
static const int float32ExactLimit = 1 << 242^{24}, the bound for exact float32 conversion: every stored integer of magnitude at most 2^{24} converts to float32 with no error.
Properties
Methods
Rational decode(int stored)The exact rational X / 2^{k} that the stored integer stored means.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${const FixedPointFormat(10).decode(1536)}');
}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.
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)');
}
}5/8 → 10 1/3 → refused (no silent rounding)
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}).
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))');
}9/16 (the points (0,0,0) and (1/4, 1/2, 1/2))
ExactLatticeState
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.
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)}');
}strut quadrance 2
Constructors
ExactLatticeState(this.format)An empty state whose stored coordinates use format.
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)}');
}node 0 = (8, 0, 0) stored, means 1
Properties
int get fingerprintA 64-bit FNV-1a fingerprint of every coordinate and strut: equal fingerprints before and after rendering prove no float wrote back.
Methods
int addNode(IVec3 stored)Adds a node at integer (stored) coordinates and returns its index.
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))}');
}indices 0, 1
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.
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)}');
}strut (0, 1), quadrance 2
void moveNode(int i, IVec3 by)Moves node i by the integer offset by (stored units).
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)}');
}node 1 now (1, 1, 1), strut quadrance 3
void transform(IMat3 g)Applies a lattice symmetry g about the origin to every node, exactly, in place.
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)}');
}after a quarter turn: (-2, 1, 3)
IVec3 node(int i)The stored coordinates of node i.
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)}');
}(5, -1, 2)
(int, int) strut(int k)The two node indices joined by strut k.
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)}');
}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.
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)]}');
}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).
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()}');
}[1, 2, 3, -4, 5, 6]
Uint32List toIndexBuffer()The strut index buffer: two node indices per strut (a copy).
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()}');
}[0, 1, 1, 2]
RenderSnapshot renderSnapshot()A one-way float view for drawing: a new RenderSnapshot that shares nothing with this state.
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}');
}float32 positions [0.25, 0.5, 0.75]
RenderSnapshot
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.
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}');
}positions [0.5, 0.0, 0.0, 0.0, 1.5, 0.0], indices [0, 1]
Properties
final Uint32List indicesThe strut index buffer: two node indices per strut, as in ExactLatticeState.toIndexBuffer.
final double maxErrorThe largest |\text{float32} - \text{exact}| over all coordinates: 0 when every stored coordinate is below 2^{24} in magnitude.
FeedbackGuard
abstract final class FeedbackGuard
Runs a render pass and proves it did not touch the exact state.
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');
}drawing 1 node(s) exact state untouched
Static
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.
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');
}
}caught: the render pass changed the exact state
ProjectiveLaws
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}.
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))}');
}Pythagoras q3 = q1 + q2 − q1q2 = 2/3: true cross law with S3 = 1: true
Static
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.
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))}');
}(1/4, 1/4, 3/4): true (1, 4, 9) (collinear in the plane, not projectively): false
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.
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)');
}(1/2, 1/2, 3/4): true (1/2, 1/2, 1): false (the plane answer is wrong here)
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.
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))}');
}residual at S3 = 1: 0 residual at S3 = 1/2: -5/48
static bool crossLawHolds<T>(ScalarField<T> f, T q1, T q2, T q3, T s3)Whether the projective cross law holds: crossLaw is zero.
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))}');
}true false
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.
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))}');
}true
Triangle
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.
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}');
}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
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.
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}');
}Q = 25, 20, 25; s = 4/5, 16/25, 4/5 quadrea 1600, all laws true
Properties
RtPlane<T> get planelate final T s1The 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.
late final T s2The 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.
late final T s3The 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.
RtMeasures<T> get measuresThe 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.
T get quadreaThe 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 isCollinearWhether the vertices are collinear: the quadrea is zero (the triple quad formula).
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}');
}(0,0) (1,2) (3,6): collinear true, quadrea 0 (0,0) (1,2) (3,5): collinear false, quadrea 4
bool get isNondegenerateWhether every side is non-null and the vertices are not collinear, so every spread is defined.
bool get satisfiesAllLawsWhether 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.
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.
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]))}');
}a × b = [0, 0, 1] a · b = 0 quadrance of (1, 2, 2) = 9 proportional: true
Constructors
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.
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)}');
}v = [1/2, -3, 2/3], dimension 3 over ℤ/7: [3, 5], 2w = [6, 3]
factory Vec.zero(ScalarField<T> field, int n)The zero vector of dimension n.
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])}');
}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.
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()}');
}vector [3/4, -1], back to a point: [3/4, -1]
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.
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))}');
}e0 = [1, 0, 0] e1 = [0, 1, 0] e2 = [0, 0, 1] e0 × e1 = [0, 0, 1]
Properties
Methods
Vec<T> scale(T k)The scalar multiple k \cdot v.
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))}');
}v = [2, -4, 6] v scaled by 1/2 = [1, -2, 3] v scaled by 0 = [0, 0, 0]
T dot(Vec<T> o)The Euclidean (blue) dot product \sum x_{i}y_{i}. For any other metric use SymmetricForm.apply.
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)');
}u·u = 9 (the blue quadrance of u) u·v = 0 (perpendicular)
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.
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]))}');
}u × v = [-3, 6, -3] perpendicular to both: 0, 0 line through (0,0) and (1,1): [-1, 1, 0]
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.
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)))}');
}u ∧ v = 5, v ∧ u = -5 parallel: 0
RtPoint<T> toRtPoint()The same planar point as riptide_algebra's RtPoint. Throws StateError unless the vector is 2-D.
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)))}');
}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.
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]))}');
}[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).
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()}');
}[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.
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()}');
}[1/2, 3] → [1/2, 3, 1] round trip: [1/2, 3]
Operators
T operator [](int i)The coordinate at index i (from 0). Throws RangeError when i is out of range.
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]}');
}v[0] = 7, v[1] = 1/2, v[2] = -3
Vec<T> operator +(Vec<T> o)The sum, coordinate by coordinate. o must have the same dimension.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('[1, 2] + [1/2, -5] = ${qv([1, 2]) + qv(['1/2', -5])}');
}[1, 2] + [1/2, -5] = [3/2, -3]
Vec<T> operator -(Vec<T> o)The difference this − o, coordinate by coordinate: the vector from the point o to this point.
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)}');
}B − A = [3, 4], its quadrance 25
Vec<T> operator -()The negated vector -v.
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}');
}−v = [-1, 2/3, 0], v + (−v) = [0, 0, 0]
bool operator ==(Object other)Exact equality: other is a Vec of the same type and dimension with equal coordinates in the field.
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]))}');
}[1/2, 1] == [2/4, 1]: true [1, 2] == [2, 4]: false, proportional: true
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.
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]))}');
}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
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.
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}');
}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.
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}');
}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.
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}');
}-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.
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]))}');
}3 -4 4 3 M e0 = [3, 4]
Properties
T get determinantThe determinant det A, exactly, by Gaussian elimination over the field. Throws StateError when the matrix is not square.
Mat<T> get inverseThe 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.
Mat<T> get adjugateThe 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.
Methods
T at(int i, int j)The entry in row i and column j (both from 0).
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)}');
}m(0,1) = 2, m(1,0) = 3
Mat<T> scale(T k)The scalar multiple k \cdot A.
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}');
}1/5 0 0 1/5 det = 1/25
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.
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]))}');
}R (5, 0) = [3, 4] R (1, 1) = [-1/5, 7/5]
Vec<T> row(int i)Row i as a vector.
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)}');
}row 0: [1, 2, 3], row 1: [4, 5, 6]
Vec<T> column(int j)Column j as a vector.
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)}');
}column 0: [1, 4] column 1: [2, 5] column 2: [3, 6]
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.
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]))}');
}x = [3, -24, 30] H x = [1, 1, 1] singular: null
String toString()One line per row, entries formatted by the field and separated by spaces.
Operators
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.
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)}');
}A² = -7/25 -24/25 24/25 -7/25 A·A⁻¹ == I: true
Mat<T> operator +(Mat<T> o)The entrywise sum. o must have the same shape.
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}');
}A + Aᵀ = 2 5 5 8
Mat<T> operator -(Mat<T> o)The entrywise difference. o must have the same shape.
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}');
}A − Aᵀ = 0 -1 1 0
bool operator ==(Object other)Exact equality: other is a Mat of the same type and shape with equal entries in the field.
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)}');
}RᵀR == I: true
SymmetricForm
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.
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)}');
}
}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
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.
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)}');
}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.
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]))}');
}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).
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]))}');
}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}.
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]))}');
}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.
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]))}');
}light ray (1,1,0,0): 0 at rest (1,0,0,0): -1 space (0,3,4,0): 25
Properties
T get determinantThe determinant \det M of the form's matrix; zero exactly when the form is degenerate.
Methods
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.
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)}');
}blue B(u, v) = 5 red B(u, v) = -1
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.
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)}');
}Q((1/2, 1/3)) = 13/36 in doubles: 0.3611111111111111
T quadrance(Vec<T> a, Vec<T> b)The quadrance between the points a and b, Q(A, B) = B(B - A, B - A).
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)}');
}Q(A, B) = 25 red: -7, green: 24
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.
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)}');
}[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.
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]))}');
}blue ⊥: false, red ⊥: true blue ⊥ (2, −1): true
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.
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)}');
}c(u, v) = 9/25, s + c = 1
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.
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]))}');
}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
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).
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]))}');
}t((1,0), (3,4)) = 16/9 t((1,0), (1,1)) = 1
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.
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)}');
}at A: 1, at B: 9/25, at C: 16/25
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).
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]))}');
}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.
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)}');
}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.
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)}');
}rotation: blue true, red false boost: blue false, red true
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.
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);
}1 1 1 1 2 2 1 2 3
Constructors
Gram(this.form, List<Vec<T>> vectors)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}');
}red Gram matrix: 3 -1 -1 -8
Properties
T get determinantThe full Gram determinant \det G; zero when the vectors are linearly dependent.
Methods
T dot(int i, int j)The dot product B(v_{i}, v_{j}) = G_{ij} of vectors i and j.
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)}');
}B(v0, v1) = 11
T quadrance(int i)The quadrance Q(v_{i}) = G_{ii} of vector i.
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)}');
}Q(v0) = 25, Q(v1) = 5
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.
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)');
}det G_{0,1} = 4 (area² of the parallelogram = 2² = 4)
det G = 36 (volume² = 6² = 36)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.
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)}');
}c = 9/25
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.
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)}');
}s = 16/25
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.
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])}');
}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.
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])}');
}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).
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)}');
}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.
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)}');
}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.
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)}');
}from spreads: -16/25, from the Gram matrix: -16/25
MetricMatrixTrig
extension MetricMatrixTrig<T> on SymmetricForm<T>
The metric-matrix forms of quadrance and spread, the B-vector product, and exact rotations of any metric.
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]))}');
}spread by wedge: 4/5, by the usual formula: 4/5
Methods
Gram<T> gram(List<Vec<T>> vs)The Gram matrix of vs in this metric, as a Gram.
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);
}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.
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]))}');
}
}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.
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)}');
}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.
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]))}');
}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.
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}');
}2/3 1/3 2/3 -1/3 -2/3 2/3 2/3 -2/3 -1/3 isometry true, det 1
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.
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))}');
}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.
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])))}');
}spread of the turn: 16/25; check: 16/25
SpreadPolynomials
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.
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()]]}
]})}');
}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
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.
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))}');
}
}S1(1/4) = 1/4 S2(1/4) = 3/4 S3(1/4) = 1 S4(1/4) = 3/4 S6(1/4) = 0
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).
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)}');
}
}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
ChromoMatrices
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).
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)}');
}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}.
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)}');
}
}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.
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)}');
}Colour.blue: det[v, Jv] = 10, Q = 10 Colour.red: det[v, Jv] = 8, Q = 8 Colour.green: det[v, Jv] = 6, Q = 6
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.
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]))}');
}l: ⟨-1 : 2 : 0⟩ m: ⟨3 : 3 : -9⟩ l meets m at [2, 1] (4, 2) on l: true
Constructors
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.
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]))}');
}l = ⟨2 : -3 : 6⟩, direction [3, 2], normal [2, -3] (0, 2) on l: true
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.
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]))}');
}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.
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]))}');
}through (1,1) with direction (2,3): ⟨-3 : 2 : 1⟩ (3, 4) on it: true
Properties
Vec<T> get normalThe vector (a, b), the Euclidean (blue) normal. In another metric use perpendicularDirection.
Methods
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.
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)}');
}l[2, 2] = 0 l[0, 1] = 1 l[1, 0] = -1
bool contains(Vec<T> p)Whether the point p lies on the line.
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]))}');
}(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.
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])))}');
}parallel to (0,1)→(1,3): true parallel to the x-axis: false
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).
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])))}');
}meet: [3/2, 1/2] parallel lines: null
Line<T> parallelThrough(Vec<T> p)The line through p parallel to this one.
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)}');
}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.
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)}');
}
}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).
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))}');
}blue: [1, -2] red: [-1, -2]
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).
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']]})}');
}foot of the perpendicular from (1, 3): [2, 1] quadrance to the line: 5
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.
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))}');
}blue null: false, red null: true
bool sameAs(Line<T> o)Whether o is the same line: its \langle a: b: c\rangle is proportional to this one's.
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}');
}⟨1:2:3⟩ same as ⟨−2:−4:−6⟩: true, equal objects: false
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.
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']]})}');
}circumcentre [3, 1], orthocentre [2, 2], centroid [8/3, 4/3] circumquadrance 10
Static
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).
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]))}');
}circumcentre: [2, 1] equal quadrances: 5, 5, 5 collinear: null
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).
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)}');
}blue orthocentre: [1, 1] red orthocentre: [1, -1]
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.
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]))}');
}centroid: [5/3, 1]
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.
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)');
}3-4-5 right triangle: 25/4 (half the hypotenuse, squared)
Polyhedron
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.
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');
}cube: 8 vertices, edge quadrance 4, 12 edges
Constructors
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).
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()}');
}octahedron edge quadrance 2, dihedral spreads {8/9}Properties
final List<Vec<T>> normalsThe outward face normals, as given; face i has normal normals[i].
final SymmetricForm<T> formThe metric used for quadrances and spreads: the Euclidean form x^{2} + y^{2} + z^{2}.
late final List<List<int>> facesFor each normal, the indices into vertices of the vertices on that face, in increasing order.
late final T edgeQuadranceThe 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.
late final List<(int, int)> edgesThe 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 eulerCharacteristicMethods
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.
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()}');
}
}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.
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()}');
}tetrahedron: {3/4} (equilateral faces: 3/4)
cube: {1}Platonic
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}).
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()}');
}
}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
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}.
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}');
}vertices [[1, 1, 1], [1, -1, -1], [-1, 1, -1], [-1, -1, 1]] dihedral spread 8/9
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.
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()}');
}8 vertices, dihedral {1}, faces {1}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}.
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()}');
}6 vertices, dihedral spread {8/9}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}.
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()}');
}12 vertices, dihedral spread {4/9}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}.
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()}');
}20 vertices, dihedral spread {4/5}
face spread {5/8 + 1/8√5}Predicates
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.
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]))}');
}orient2d (counter-clockwise): 1 orient2d (clockwise): -1 orient2d (collinear): 0 incircle (0,0) inside unit circle points: 1
Constructors
const Predicates(this.field)The predicates over field, such as Predicates(Q).
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]))}');
}orient2d: 1
Properties
Methods
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.
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))]))}');
}left turn 1, right turn -1, straight 0 (4, 2 + 10⁻³⁰): 1
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).
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]))}');
}true, false
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.
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']))}');
}origin: 1, (0, −1): 0, (2, 2): -1 (3/5, −4/5), exactly on: 0
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.
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]))}');
}above 1, below -1, in 0
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.
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]))}');
}true false
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.
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]))}');
}origin: 1 (2, 0, 0): -1 (0, 0, −1): 0
FloatPredicates
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).
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)}');
}orient2d: 1
Static
static int exactFallbacksHow many calls since program start (or the last reset) fell back to exact arithmetic, across all four tests. For benchmarks; assign 0 to reset.
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.
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))}');
}naive float determinant: 0.0 FloatPredicates.orient2d: 1 exact over ℚ: 1
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.
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)');
}origin: 1 (0, −1): 0 (0.6, −0.8): -1 (0.6 and 0.8 are not exact doubles)
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.
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])}');
}just above: 1 in the plane: 0
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.
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])}');
}origin: 1 (0, −1, 0): 0 (3, 0, 0): -1
ProjectivePlane
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.
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))}');
}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
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.
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))}');
}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}.
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))}');
}[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).
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))}');
}q([1:0:0], [0:1:0]) = 1 q([1:0:0], [1:1:0]) = 1/2
Properties
Methods
Vec<T> point(T x, T y, T z)The point [x: y: z].
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))}');
}a = [1/2, 1/3, 1]; same point as [3:2:6]: true
Vec<T> pointOf(int x, int y, int z)The point [x: y: z] from ints.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
final h = ProjectivePlane.hyperbolic(Q);
print('${h.pointOf(1, 2, 5)}');
}[1, 2, 5]
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.
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)}');
}line through [0:0:1] and [1:1:3]: [-1, 1, 0] [2:2:5] on it: true
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.
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)}');
}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).
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))}');
}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).
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)}');
}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.
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)}');
}[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.
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]))}');
}⟨1:0:−1⟩ null: true, ⟨1:0:−2⟩ null: false
bool incident(Vec<T> a, Vec<T> l)Whether the point a lies on the line l: a \cdot L = 0.
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)}');
}[2:2:7] on x = y: true, [1:2:3]: false
bool collinear(Vec<T> a, Vec<T> b, Vec<T> c)Whether the three points lie on one line: \det[a b c] = 0.
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))}');
}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.
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]))}');
}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.
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)}');
}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⊥.
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)}');
}x = 0 ⊥ y = 0: true, spread 1
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.
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))}');
}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
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.
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)');
}S = 1/2 (at the centre it agrees with the Euclidean spread 1/2)
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).
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)}');
}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).
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)))}');
}hyperbolic orthocentre: [0, 0, -6] third altitude passes through it: true
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}).
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}');
}q = -1/2, -1/3, -1/8 S = 1, 2/3, 1/4
ProjectiveTriangle
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.
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}');
}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.
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}');
}elliptic q = 2/3, 2/3, 1; nondegenerate true
Properties
late final Vec<T> l1The 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}).
late final Vec<T> l2The 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}).
late final Vec<T> l3The 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}).
late final T q1The 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}).
late final T q2The 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}).
late final T q3The 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}).
late final T s1The 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}.
late final T s2The 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}.
late final T s3The 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 isNondegenerateWhether the vertices are not collinear and no vertex or side is null, so every quadrance and spread is defined.
Methods
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.
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'));
}spreadLaw: true crossLaw: true crossLaw1: true crossDualLaw: true
FieldRatio
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.
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)}');
}spread 1/2, cross 1/2, twist 1
Constructors
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.
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]))}');
}8
Properties
Methods
T fromInt(int n)The integer n as a field element.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${FieldRatio(SymmetricForm.blue(Q)).fromInt(4)}');
}4
T add(T a, T b)The field sum a + b.
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))}');
}1/2
T sub(T a, T b)The field difference a - b.
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))}');
}1/6
T mul(T a, T b)The field product a \cdot b.
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))}');
}3/2
T div(T a, T b)The field quotient a / b; throws the field's division error when b = 0 (UnsupportedError over \mathbb{Q}).
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))}');
}3/2
bool isZero(T a, T scale)Whether a is exactly zero; scale is ignored.
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))}');
}true, false
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).
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${FieldRatio(SymmetricForm.blue(Q)).toDouble(rat(1, 8))}');
}0.125
Vec<T> vector(List<int> coords)The vector with integer coordinates coords.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${FieldRatio(SymmetricForm.blue(Q, 3)).vector([1, -2, 3])}');
}[1, -2, 3]
Vec<T> vadd(Vec<T> a, Vec<T> b)The vector sum a + b.
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]))}');
}[4, 6]
Vec<T> vsub(Vec<T> a, Vec<T> b)The vector difference a - b.
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]))}');
}[-2, -2]
Vec<T> vscale(T k, Vec<T> v)The scalar multiple k v.
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]))}');
}[3/2, 2]
bool same(Vec<T> a, Vec<T> b, T scale)Whether a and b have exactly equal coordinates; scale is ignored.
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))}');
}true, false
T size(Vec<T> v)The Euclidean quadrance x^{2} + y^{2} (+ z^{2}) of the coordinates, whatever form is.
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]))})');
}Euclidean size of (3, 4): 25 (red quadrance -7)
T dot(Vec<T> a, Vec<T> b)B(a, b) in form.
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]))}');
}red B((2,1), (1,3)) = -1
T quadrance(Vec<T> a)The quadrance Q(a) = B(a, a) in form.
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]))}');
}49
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).
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]))}');
}45/49
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.
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]))}');
}4/49
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.
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]))}');
}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.
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]))}');
}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.
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]))}');
}1/2
T gramDeterminant(List<Vec<T>> vs)The determinant of the Gram matrix B(v_{i}, v_{j}) of vs in form.
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)');
}36 (volume² 36)
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.
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]))}');
}[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.
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])])}');
}3-D: [0, 0, 1] red 2-D: [1, 2]
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.
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)}');
}[3/5, 4/5, 0], quadrance 1
Reflection
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.
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]))}');
}(0, 0) ↦ [1, 1], (0, 1) stays [0, 1]
Constructors
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.
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)}');
}blue reflection of (3,1): [1, -3] red reflection of (3,1): [11/3, 7/3]
Properties
final Vec<T> throughA point p on the hyperplane; it and every other point of the hyperplane stay fixed.
RigidMotion<T> get motionThe 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
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.
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))}');
}[5, 0] ↦ [7/5, -24/5], quadrance kept: 25
ReflectionDecomposition
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).
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');
}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.
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])}');
}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.
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}');
}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.
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)}');
}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.
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');
}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.
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)}');
}t = 1 rotation(1/2)·rotation(1/3) == rotation(1): true
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.
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');
}2 parallel reflections slide (1, 1) to [4, 1]
DehnScreen
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.
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)}');
}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.
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)}');
}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.
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)])}');
}cube: true tetrahedron: false
RtQuaternion
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.
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}');
}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
RtQuaternion(this.field, this.w, this.x, this.y, this.z)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]))}');
}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.
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)}');
}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
T get normThe norm |q|^{2} = w^{2} + x^{2} + y^{2} + z^{2} (the blue quadrance of q, exactly). It is multiplicative:
| pq | ² = | p | ² | q | ². |
|---|
RtQuaternion<T> get inverseThe 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.
int get hashCodeMethods
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.
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)}');
}1/9 8/9 4/9 8/9 1/9 -4/9 -4/9 4/9 -7/9 det 1, isometry true
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.
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]))}');
}(1, 0, 0) ↦ [3/5, 4/5, 0] axis (0, 0, 1) fixed: [0, 0, 1]
Operators
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.
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]))}');
}i·j = (0, 0, 0, 1), j·i = (0, 0, 0, -1) rotate by b then a == rotate by a·b: true
RtQuaternion<T> operator +(RtQuaternion<T> o)The coordinatewise sum this + o.
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}');
}a + b = (3/2, 2, 0, 5)
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).
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()}');
}q == 2q: false, same rotation: true
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.
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}');
}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.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.
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}');
}(1/2, 1/2, 1/2, 1/2), norm 1
factory Hurwitz(int w, int x, int y, int z)The Lipschitz (all-integer) quaternion w + \xi + yj + zk.
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');
}(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).
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}');
}(1/2, -1/2, 3/2, 1/2) = (1/2, -1/2, 3/2, 1/2), norm 3
Static
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)).
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(' '));
}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)
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.
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}');
}gcd = (1, 2, 0, 0), norm 5
Properties
BigInt get normThe norm w^{2} + x^{2} + y^{2} + z^{2} (an integer for every Hurwitz integer).
int get hashCodeMethods
RtQuaternion<Rational> toQuaternion()The same quaternion as an RtQuaternion over Q.
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]))}');
}as a rational quaternion: (1/2, 1/2, 1/2, 1/2) (1, 0, 0) ↦ [0, 1, 0]
(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.
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}');
}q = (3, 0, 1, -1), r = (0, -1, 0, 0), N(r) = 1 < N(b) = 6 q·b + r == a: true
String toString()(w, x, y, z) with rational coordinates, such as (1/2, 1/2, 1/2, 1/2).
Operators
Hurwitz operator *(Hurwitz o)The Hamilton product this·o, again a Hurwitz integer. Not commutative.
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}');
}i·j = (0, 0, 0, 1), j·i = (0, 0, 0, -1)
Hurwitz operator +(Hurwitz o)The sum this + o, again a Hurwitz integer.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${Hurwitz(1, 0, 0, 0) + Hurwitz.half(1, 1, 1, 1)}');
}(3/2, 1/2, 1/2, 1/2)
Hurwitz operator -(Hurwitz o)The difference this − o, again a Hurwitz integer.
import 'package:riptide_rational_geometry/riptide_rational_geometry.ray';
void main() {
print('${Hurwitz(2, 1, 0, 0) - Hurwitz.half(1, 1, 1, 1)}');
}(3/2, 1/2, -1/2, -1/2)
bool operator ==(Object other)Whether other is the same Hurwitz integer (equal coordinates).
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)}');
}ω³ == 1 for ω = (−1 + i + j + k)/2: true
AffineMap
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.
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}');
}m(p) = [10/3, 1] m⁻¹(m(p)) = [1/3, 1] m ∘ m⁻¹: linear part 1 0 0 1 translation [0, 0]
Constructors
AffineMap(this.linear, this.translation)The map x ↦ linear x + translation. Throws ArgumentError unless linear is square and translation has the same dimension.
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]))}');
}(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.
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]))}');
}(3, 7) ↦ [3, 7]
factory AffineMap.translation(Vec<T> t)The pure shift x \mapsto x + t (A = I).
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]))}');
}(0, 0) ↦ [1/2, -1], twice: [1, -2]
Properties
int get dimThe dimension n of the space the map acts on.
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}');
}dim 3, linear part: 1 0 0 0 1 0 0 0 1 translation [1, 2, 3]
AffineMap<T> get inverseThe 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.
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}');
}
}inverse: x ↦ A⁻¹ x + [-4, 5] m⁻¹(m((5, 7))) = [5, 7] singular A: singular matrix
Methods
Vec<T> apply(Vec<T> x)The image A x + t of the point x, exactly.
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)}');
}[0, 0] ↦ [1, 0] [5, 0] ↦ [4, 4] [0, 5] ↦ [-3, 3]
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.
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]))}');
}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.
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]))}');
}homogeneous matrix: 1 2 3 0 1 4 0 0 1 same image: [6, 5] = [6, 5]
RigidMotion
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.
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}');
}Q before 5, after 5 proper: true
Constructors
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.
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}');
}
}reflection in the x-axis: proper false, (2, 3) ↦ [2, -3] shear: the linear part is not an isometry of the form
Properties
RigidMotion<T> get inverseThe 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.
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])))}');
}m⁻¹ is a rigid motion: true m⁻¹(m((7, -3))) = [7, -3]
bool get isProperWhether the motion is proper (det A = 1, like a rotation) rather than improper (det A = -1 for a nondegenerate form, like a reflection).
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}');
}rotation: proper true, det 1 reflection: proper false, det -1 two reflections: proper true
Methods
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.
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}');
}rotation twice: linear part -7/25 -24/25 24/25 -7/25 still proper: true
ProjectiveMap
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.
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)');
}(1, 1) ↦ [1/2, 1/2], (−1, 0) ↦ null (sent to infinity)
Constructors
ProjectiveMap(this.matrix)The map with homogeneous matrix matrix. Throws ArgumentError when matrix is singular.
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]))}');
}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).
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']))}');
}[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
final Mat<T> matrixThe homogeneous matrix, any one of the proportional matrices that give this map.
ProjectiveMap<T> get inverseThe 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.
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)))}');
}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.
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)');
}[−1 : 0 : 1] ↦ [-1, 0, 0] (w = 0: a point at infinity)
Vec<T>? apply(Vec<T> x)The image of the affine point x (n coordinates), or null when it is sent to infinity.
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]))}');
}(1, 2) ↦ [1/2, 1], (−1, 5) ↦ null
ProjectiveMap<T> compose(ProjectiveMap<T> other)The composite this ∘ other: apply other first, then this map.
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)))}');
}a ∘ b is the identity: true
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.
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}');
}I ~ 7I: true, equal matrices: false