tiny-exact-math 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +81 -0
  3. package/Rational.js +296 -0
  4. package/package.json +34 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Brent Buffham
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,81 @@
1
+ # tiny-exact-math
2
+
3
+ Minimal rational arithmetic library for exact geometric predicates in pure JavaScript. Zero dependencies — uses native `BigInt`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ npm install tiny-exact-math
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```js
14
+ import { Rational, fromNumber, determinant, determinant3 } from 'tiny-exact-math';
15
+
16
+ // Create rationals
17
+ const a = new Rational(1n, 3n); // 1/3
18
+ const b = fromNumber(0.1); // exact representation of 0.1
19
+
20
+ // Arithmetic
21
+ a.add(b); // returns new Rational
22
+ a.subtract(b);
23
+ a.multiply(b);
24
+ a.divide(b);
25
+
26
+ // 2D orientation test (sign of 2×2 determinant)
27
+ // Returns +1 (counter-clockwise), -1 (clockwise), or 0 (collinear)
28
+ determinant(
29
+ { x: 0, y: 0 },
30
+ { x: 1, y: 0 },
31
+ { x: 0, y: 1 }
32
+ ); // +1
33
+
34
+ // 3D plane-side test (sign of 3×3 determinant)
35
+ // Returns +1 (above plane), -1 (below), or 0 (coplanar)
36
+ determinant3(
37
+ { x: 0, y: 0, z: 0 },
38
+ { x: 1, y: 0, z: 0 },
39
+ { x: 0, y: 1, z: 0 },
40
+ { x: 0, y: 0, z: 1 }
41
+ ); // +1
42
+ ```
43
+
44
+ ## API
45
+
46
+ ### `new Rational(numerator, denominator?)`
47
+
48
+ Create a rational number from BigInt or number values. Automatically normalised to lowest terms with a positive denominator.
49
+
50
+ ### `fromNumber(n)`
51
+
52
+ Convert a JavaScript `number` (integer or float) to an exact `Rational`. Uses the shortest decimal round-trip representation to avoid precision loss.
53
+
54
+ ### `gcd(a, b)`
55
+
56
+ Greatest common divisor of two `BigInt` values.
57
+
58
+ ### Rational instance methods
59
+
60
+ | Method | Description |
61
+ |--------|-------------|
62
+ | `add(other)` | Addition |
63
+ | `subtract(other)` | Subtraction |
64
+ | `multiply(other)` | Multiplication |
65
+ | `divide(other)` | Division |
66
+ | `sign()` | Returns `-1`, `0`, or `1` |
67
+ | `isZero()` | Returns `true` if zero |
68
+ | `toNumber()` | Convert to JS `number` (may lose precision) |
69
+ | `toString()` | Human-readable string (`"1/3"`) |
70
+
71
+ ### `determinant(p1, p2, p3)`
72
+
73
+ Exact 2D orientation test. Returns the sign of the 2×2 determinant formed by three `{x, y}` points.
74
+
75
+ ### `determinant3(p1, p2, p3, p4)`
76
+
77
+ Exact 3D plane-side test. Returns the sign of the 3×3 determinant formed by four `{x, y, z}` points.
78
+
79
+ ## License
80
+
81
+ MIT
package/Rational.js ADDED
@@ -0,0 +1,296 @@
1
+ /**
2
+ * tiny-exact-math
3
+ * Minimal rational arithmetic library for exact geometric predicates.
4
+ */
5
+
6
+ /**
7
+ * Compute the greatest common divisor of two BigInts using the Euclidean
8
+ * algorithm. The result is always non-negative.
9
+ *
10
+ * @param {bigint} a
11
+ * @param {bigint} b
12
+ * @returns {bigint}
13
+ */
14
+ export function gcd(a, b) {
15
+ a = a < 0n ? -a : a;
16
+ b = b < 0n ? -b : b;
17
+ while (b !== 0n) {
18
+ const t = b;
19
+ b = a % b;
20
+ a = t;
21
+ }
22
+ return a;
23
+ }
24
+
25
+ /**
26
+ * Convert a JavaScript number (integer or floating-point) to a Rational.
27
+ *
28
+ * Strategy: use `String(n)`, which produces the *shortest* decimal
29
+ * representation that round-trips back to the same IEEE 754 double (Grisu /
30
+ * Ryu algorithm in V8). Parse the resulting decimal string into a
31
+ * numerator/denominator pair, handling the sign, fractional part, and
32
+ * optional scientific-notation exponent separately to avoid BigInt parsing
33
+ * errors (e.g. BigInt("-05") would throw).
34
+ *
35
+ * @param {number} n
36
+ * @returns {Rational}
37
+ */
38
+ export function fromNumber(n) {
39
+ if (!isFinite(n)) {
40
+ throw new RangeError("Cannot convert non-finite number to Rational");
41
+ }
42
+ if (n === 0) return new Rational(0n, 1n);
43
+
44
+ const str = String(n);
45
+ const negative = str.charCodeAt(0) === 45; // '-'
46
+ const abs = negative ? str.slice(1) : str;
47
+
48
+ // Handle scientific notation produced for very large / very small values
49
+ // e.g. "1.5e-7" or "1e+21"
50
+ const eIdx = abs.indexOf("e");
51
+ if (eIdx !== -1) {
52
+ const base = abs.slice(0, eIdx);
53
+ const exp = parseInt(abs.slice(eIdx + 1), 10);
54
+ const r = _parseDecimalString(base, negative);
55
+ const pow = 10n ** BigInt(Math.abs(exp));
56
+ return exp >= 0
57
+ ? new Rational(r.numerator * pow, r.denominator)
58
+ : new Rational(r.numerator, r.denominator * pow);
59
+ }
60
+
61
+ return _parseDecimalString(abs, negative);
62
+ }
63
+
64
+ /**
65
+ * Parse a plain decimal string (no sign, no exponent) into a Rational.
66
+ * @param {string} abs – digits with optional "."
67
+ * @param {boolean} negative
68
+ * @returns {Rational}
69
+ */
70
+ function _parseDecimalString(abs, negative) {
71
+ const dotIndex = abs.indexOf(".");
72
+ if (dotIndex === -1) {
73
+ const num = negative ? -BigInt(abs) : BigInt(abs);
74
+ return new Rational(num, 1n);
75
+ }
76
+
77
+ const intDigits = abs.slice(0, dotIndex) || "0";
78
+ const fracDigits = abs.slice(dotIndex + 1);
79
+ const combined = intDigits + fracDigits; // sign removed, safe for BigInt
80
+ const num = negative ? -BigInt(combined) : BigInt(combined);
81
+ const den = 10n ** BigInt(fracDigits.length);
82
+ return new Rational(num, den);
83
+ }
84
+
85
+ /**
86
+ * A rational number stored as two BigInts (numerator and denominator).
87
+ * The value is always kept in lowest terms with a non-negative denominator.
88
+ */
89
+ export class Rational {
90
+ /**
91
+ * @param {bigint|number} numerator
92
+ * @param {bigint|number} denominator
93
+ */
94
+ constructor(numerator, denominator = 1n) {
95
+ let num = BigInt(numerator);
96
+ let den = BigInt(denominator);
97
+
98
+ if (den === 0n) {
99
+ throw new RangeError("Denominator must not be zero");
100
+ }
101
+
102
+ // Normalise: keep denominator positive
103
+ if (den < 0n) {
104
+ num = -num;
105
+ den = -den;
106
+ }
107
+
108
+ const g = gcd(num < 0n ? -num : num, den);
109
+ this.numerator = num / g;
110
+ this.denominator = den / g;
111
+ }
112
+
113
+ // ── Arithmetic ────────────────────────────────────────────────────────────
114
+
115
+ /**
116
+ * Return a new Rational equal to this + other.
117
+ * @param {Rational} other
118
+ * @returns {Rational}
119
+ */
120
+ add(other) {
121
+ return new Rational(
122
+ this.numerator * other.denominator + other.numerator * this.denominator,
123
+ this.denominator * other.denominator
124
+ );
125
+ }
126
+
127
+ /**
128
+ * Return a new Rational equal to this - other.
129
+ * @param {Rational} other
130
+ * @returns {Rational}
131
+ */
132
+ subtract(other) {
133
+ return new Rational(
134
+ this.numerator * other.denominator - other.numerator * this.denominator,
135
+ this.denominator * other.denominator
136
+ );
137
+ }
138
+
139
+ /**
140
+ * Return a new Rational equal to this * other.
141
+ * @param {Rational} other
142
+ * @returns {Rational}
143
+ */
144
+ multiply(other) {
145
+ return new Rational(
146
+ this.numerator * other.numerator,
147
+ this.denominator * other.denominator
148
+ );
149
+ }
150
+
151
+ /**
152
+ * Return a new Rational equal to this / other.
153
+ * @param {Rational} other
154
+ * @returns {Rational}
155
+ */
156
+ divide(other) {
157
+ if (other.numerator === 0n) {
158
+ throw new RangeError("Division by zero");
159
+ }
160
+ return new Rational(
161
+ this.numerator * other.denominator,
162
+ this.denominator * other.numerator
163
+ );
164
+ }
165
+
166
+ // ── Comparison ────────────────────────────────────────────────────────────
167
+
168
+ /**
169
+ * Return the sign of this rational: -1, 0, or 1.
170
+ * @returns {number}
171
+ */
172
+ sign() {
173
+ if (this.numerator === 0n) return 0;
174
+ return this.numerator > 0n ? 1 : -1;
175
+ }
176
+
177
+ /**
178
+ * Return true if this rational equals zero.
179
+ * @returns {boolean}
180
+ */
181
+ isZero() {
182
+ return this.numerator === 0n;
183
+ }
184
+
185
+ /**
186
+ * Convert to a JavaScript number (may lose precision).
187
+ * @returns {number}
188
+ */
189
+ toNumber() {
190
+ return Number(this.numerator) / Number(this.denominator);
191
+ }
192
+
193
+ /**
194
+ * Human-readable string representation.
195
+ * @returns {string}
196
+ */
197
+ toString() {
198
+ if (this.denominator === 1n) return String(this.numerator);
199
+ return `${this.numerator}/${this.denominator}`;
200
+ }
201
+ }
202
+
203
+ // ── Geometric predicate ──────────────────────────────────────────────────────
204
+
205
+ /**
206
+ * Compute the orientation (sign of the 2×2 determinant) of three 2-D points.
207
+ *
208
+ * Given points p1, p2, p3 each with numeric `x` and `y` properties, the
209
+ * determinant is:
210
+ *
211
+ * | p2.x - p1.x p3.x - p1.x |
212
+ * | p2.y - p1.y p3.y - p1.y |
213
+ *
214
+ * = (p2.x - p1.x)(p3.y - p1.y) - (p3.x - p1.x)(p2.y - p1.y)
215
+ *
216
+ * All coordinates are converted to exact Rationals before the computation so
217
+ * the result is free of floating-point rounding error.
218
+ *
219
+ * @param {{ x: number, y: number }} p1
220
+ * @param {{ x: number, y: number }} p2
221
+ * @param {{ x: number, y: number }} p3
222
+ * @returns {-1 | 0 | 1} sign of the determinant
223
+ */
224
+ export function determinant(p1, p2, p3) {
225
+ const x1 = fromNumber(p1.x);
226
+ const y1 = fromNumber(p1.y);
227
+ const x2 = fromNumber(p2.x);
228
+ const y2 = fromNumber(p2.y);
229
+ const x3 = fromNumber(p3.x);
230
+ const y3 = fromNumber(p3.y);
231
+
232
+ const dx2 = x2.subtract(x1);
233
+ const dy2 = y2.subtract(y1);
234
+ const dx3 = x3.subtract(x1);
235
+ const dy3 = y3.subtract(y1);
236
+
237
+ // det = dx2*dy3 - dx3*dy2
238
+ const det = dx2.multiply(dy3).subtract(dx3.multiply(dy2));
239
+
240
+ return det.sign();
241
+ }
242
+
243
+ /**
244
+ * Compute the orientation (sign of the 3×3 determinant) of four 3-D points.
245
+ *
246
+ * Given points p1, p2, p3, p4 each with numeric `x`, `y`, and `z`
247
+ * properties, the determinant is:
248
+ *
249
+ * | p2.x-p1.x p3.x-p1.x p4.x-p1.x |
250
+ * | p2.y-p1.y p3.y-p1.y p4.y-p1.y |
251
+ * | p2.z-p1.z p3.z-p1.z p4.z-p1.z |
252
+ *
253
+ * Returns +1 if p4 is above the plane defined by p1→p2→p3 (right-hand rule),
254
+ * -1 if below, and 0 if coplanar.
255
+ *
256
+ * All coordinates are converted to exact Rationals before the computation so
257
+ * the result is free of floating-point rounding error.
258
+ *
259
+ * @param {{ x: number, y: number, z: number }} p1
260
+ * @param {{ x: number, y: number, z: number }} p2
261
+ * @param {{ x: number, y: number, z: number }} p3
262
+ * @param {{ x: number, y: number, z: number }} p4
263
+ * @returns {-1 | 0 | 1} sign of the determinant
264
+ */
265
+ export function determinant3(p1, p2, p3, p4) {
266
+ const x1 = fromNumber(p1.x);
267
+ const y1 = fromNumber(p1.y);
268
+ const z1 = fromNumber(p1.z);
269
+ const x2 = fromNumber(p2.x);
270
+ const y2 = fromNumber(p2.y);
271
+ const z2 = fromNumber(p2.z);
272
+ const x3 = fromNumber(p3.x);
273
+ const y3 = fromNumber(p3.y);
274
+ const z3 = fromNumber(p3.z);
275
+ const x4 = fromNumber(p4.x);
276
+ const y4 = fromNumber(p4.y);
277
+ const z4 = fromNumber(p4.z);
278
+
279
+ // Column vectors relative to p1
280
+ const a = x2.subtract(x1);
281
+ const b = x3.subtract(x1);
282
+ const c = x4.subtract(x1);
283
+ const d = y2.subtract(y1);
284
+ const e = y3.subtract(y1);
285
+ const f = y4.subtract(y1);
286
+ const g = z2.subtract(z1);
287
+ const h = z3.subtract(z1);
288
+ const i = z4.subtract(z1);
289
+
290
+ // det = a(ei - fh) - b(di - fg) + c(dh - eg)
291
+ const det = a.multiply(e.multiply(i).subtract(f.multiply(h)))
292
+ .subtract(b.multiply(d.multiply(i).subtract(f.multiply(g))))
293
+ .add(c.multiply(d.multiply(h).subtract(e.multiply(g))));
294
+
295
+ return det.sign();
296
+ }
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "tiny-exact-math",
3
+ "version": "0.0.1",
4
+ "description": "Minimal rational arithmetic library for exact geometric predicates in pure JavaScript",
5
+ "type": "module",
6
+ "main": "Rational.js",
7
+ "exports": {
8
+ ".": "./Rational.js"
9
+ },
10
+ "files": [
11
+ "Rational.js"
12
+ ],
13
+ "keywords": [
14
+ "rational",
15
+ "exact-arithmetic",
16
+ "bigint",
17
+ "determinant",
18
+ "geometric-predicates",
19
+ "orientation",
20
+ "mesh",
21
+ "boolean",
22
+ "trimesh"
23
+ ],
24
+ "author": "Brent Buffham",
25
+ "license": "MIT",
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "git+https://github.com/brentbuffham/tiny-exact-math.git"
29
+ },
30
+ "bugs": {
31
+ "url": "https://github.com/brentbuffham/tiny-exact-math/issues"
32
+ },
33
+ "homepage": "https://github.com/brentbuffham/tiny-exact-math#readme"
34
+ }