trilean 1.7.12 → 1.8.0

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 (50) hide show
  1. package/README.md +33 -13
  2. package/dist/builtin-functions.cjs +129 -0
  3. package/dist/builtin-functions.d.cts +13 -0
  4. package/dist/builtin-functions.d.ts +13 -0
  5. package/dist/builtin-functions.js +128 -0
  6. package/dist/complex-division.cjs +48 -0
  7. package/dist/complex-division.d.cts +25 -0
  8. package/dist/complex-division.d.ts +25 -0
  9. package/dist/complex-division.js +47 -0
  10. package/dist/duration-order.cjs +84 -0
  11. package/dist/duration-order.d.cts +22 -0
  12. package/dist/duration-order.d.ts +22 -0
  13. package/dist/duration-order.js +82 -0
  14. package/dist/evaluate-document.cjs +87 -0
  15. package/dist/evaluate-document.d.cts +40 -0
  16. package/dist/evaluate-document.d.ts +40 -0
  17. package/dist/evaluate-document.js +86 -0
  18. package/dist/evaluator-collection.d.cts +1 -1
  19. package/dist/evaluator-collection.d.ts +1 -1
  20. package/dist/evaluator-factory.d.cts +1 -1
  21. package/dist/evaluator-factory.d.ts +1 -1
  22. package/dist/evaluator-indeterminacy-helpers.d.cts +1 -1
  23. package/dist/evaluator-indeterminacy-helpers.d.ts +1 -1
  24. package/dist/evaluator-operations.cjs +75 -24
  25. package/dist/evaluator-operations.d.cts +3 -3
  26. package/dist/evaluator-operations.d.ts +3 -3
  27. package/dist/evaluator-operations.js +74 -23
  28. package/dist/evaluator.d.cts +1 -1
  29. package/dist/evaluator.d.ts +1 -1
  30. package/dist/functions.d.cts +8 -4
  31. package/dist/functions.d.ts +8 -4
  32. package/dist/index.cjs +8 -1
  33. package/dist/index.d.cts +5 -2
  34. package/dist/index.d.ts +5 -2
  35. package/dist/index.js +5 -2
  36. package/dist/input-resolvers.cjs +63 -0
  37. package/dist/input-resolvers.d.cts +19 -0
  38. package/dist/input-resolvers.d.ts +19 -0
  39. package/dist/input-resolvers.js +61 -0
  40. package/dist/integer-power.cjs +20 -0
  41. package/dist/integer-power.d.cts +13 -0
  42. package/dist/integer-power.d.ts +13 -0
  43. package/dist/integer-power.js +19 -0
  44. package/dist/plain-record.cjs +8 -0
  45. package/dist/plain-record.d.cts +4 -0
  46. package/dist/plain-record.d.ts +4 -0
  47. package/dist/plain-record.js +7 -0
  48. package/dist-cli/trilean.mjs +1745 -0
  49. package/package.json +5 -1
  50. package/schemas/trilean.schema.json +1 -1
package/README.md CHANGED
@@ -167,14 +167,32 @@ const matching = orders.filter((_, i) => results[i]?.status === "definite" && re
167
167
 
168
168
  See [`and`/`or`](#not-and-or), [`compare`](#compare), [`textCompare`](#textcompare), and [`memberOf`](#memberof) for the full node-kind reference.
169
169
 
170
+ ## Command line
171
+
172
+ The package ships a `trilean` command that evaluates a tree stored as JSON, for a shell script or an agent skill that holds its formulae as data and has no host program to embed the library in:
173
+
174
+ ```sh
175
+ npx trilean evaluate formula.json --inputs inputs.json
176
+ ```
177
+
178
+ `formula.json` is a predicate tree or an expression tree (`-` reads it from standard input; the tree and `--inputs` cannot both be `-`). The root's `kind` says which; only a root `treeReference`, valid in both, needs `--as predicate` or `--as expression`. `inputs.json` is an object of named values, one per `reference` key: a plain number, string or boolean, or a complete computed value when the input needs a unit, for example `{ "kind": "number", "value": 2, "unit": { "m": 1 } }`. Units are dimensional-exponent maps and are never converted, exactly as in the library. Numbers must be finite (`1e999` parses to infinity and is refused), a field a computed value does not define is dropped, and a repeated key in the JSON, like a repeated `--inputs` flag, takes the last value.
179
+
180
+ The result is printed as JSON in the `Evaluation` shape, a `definite` value or an `indeterminate` reason (see [The evaluation model](#the-evaluation-model)). The exit status separates the three outcomes a script cares about: `0` for a definite result, `1` for an indeterminate one, `2` when no result was printed (bad usage, an unreadable file, JSON that is malformed, a tree or an input that fails validation, a tree that folds or quantifies over a collection, which the command has none to supply, or a result JSON cannot carry, which the built-in registry never produces). Everything that is not a result goes to standard error, the usage text included unless `--help` asked for it, and problems with the tree or an input are one `path: message` line each. A reader of standard output that closes early (`| true`) does not change the exit status or print an error.
181
+
182
+ `call` nodes resolve against `builtinFunctions`, which the library also exports (frozen, so changing the export cannot change what the command resolves): `minimum` and `maximum` (one or more numbers sharing a unit), `absoluteValue`, `round` (halves away from zero, working on the decimal number as written, so `round(1.005, 2)` is `1.01`, with an optional count of decimal places, and a value too large to have a digit at that precision returned unchanged), `squareRoot`, `exponential`, and `logarithm` (natural, or to an optional base, exact for powers of 10 and 2). They take real numbers only: a complex value is refused by every one of them, `absoluteValue` included. They follow the unit rules above: `minimum`, `maximum`, `absoluteValue` and `round` keep the argument's unit, `squareRoot` halves each dimension's exponent and refuses an odd one, and `exponential` and `logarithm` accept dimensionless numbers only. An argument a function cannot accept (the wrong kind or count, or mismatched units, as in `minimum(1 m, 2)`) is `wrong-type`; an argument of the right kind outside the function's domain, or a result that is not a finite number, is `domain-error`; and any other name is `wrong-type`.
183
+
184
+ Inputs are scalar, so the command has no collection, table, delegate or tree store to hand a `fold`, `some`, `every`, `lookup`, `delegate` or `treeReference` node. A `lookup` is `not-found`, a `delegate` or `treeReference` is `wrong-type`, and a tree that folds or quantifies over a collection exits `2` rather than treating the collection as empty. That holds even when another operand would settle the answer: `and(false, some(...))` still exits `2`, because the synchronous evaluator asks for the collection before it combines the two. For those trees, embed the library and supply the [resolvers](#resolvers) yourself.
185
+
186
+ The same evaluation is available in code as `evaluateDocument`, with `parseInputs` and `createInputResolvers` for the named-input resolvers it uses.
187
+
170
188
  ## Build, test, and lint
171
189
 
172
190
  ```sh
173
191
  pnpm install
174
- pnpm build # tsdown -> dist/, then generates schemas/trilean.schema.json
192
+ pnpm build # tsdown -> dist/ and the trilean command in dist-cli/, then generates schemas/trilean.schema.json
175
193
  pnpm test # unit suite, against src/
176
194
  pnpm test:integration # multi-kind composition, schema-pipeline, and function-registry/delegate tests, against src/
177
- pnpm test:smoke # builds first, then checks dist/ in both ESM and CJS plus the generated JSON Schema
195
+ pnpm test:smoke # builds first, then checks dist/ in both ESM and CJS, the generated JSON Schema and the built trilean command
178
196
  pnpm test:workers # runs the evaluator inside a real Cloudflare Workers isolate
179
197
  pnpm lint
180
198
  pnpm typecheck
@@ -486,11 +504,11 @@ A reference to a single external value, identified by an opaque `key` whose mean
486
504
 
487
505
  ### `arithmetic`, `negate`
488
506
 
489
- Binary arithmetic (`add`/`subtract`/`multiply`/`divide`/`power`/`modulo`) and unary negation, each over `number` computed values by default, with the temporal exceptions listed under [Temporal values](#temporal-values) and the complex ones under [Complex values](#complex-values) below. `negate` is an explicit node — never sugar for "zero minus the value" — because it also applies to `duration` values (negating a duration reverses its direction) where "zero minus" has no natural literal-zero counterpart; over a `complex` value it flips both components. Division by zero, or any operator given an operand outside its mathematical domain, is `domain-error`; a non-numeric, non-temporal operand where a number was required is `wrong-type`; any operand that is itself indeterminate makes the whole node indeterminate, with no rescuing value on the other side (see [Three-valued propagation rules](#three-valued-propagation-rules)).
507
+ Binary arithmetic (`add`/`subtract`/`multiply`/`divide`/`power`/`modulo`) and unary negation, each over `number` computed values by default, with the temporal exceptions listed under [Temporal values](#temporal-values) and the complex ones under [Complex values](#complex-values) below. `negate` is an explicit node — never sugar for "zero minus the value" — because it also applies to `duration` values (negating a duration reverses its direction) where "zero minus" has no natural literal-zero counterpart; over a `complex` value it flips both components. Division by zero, any operator given an operand outside its mathematical domain, or a result too large to represent (an overflow to infinity, which JSON cannot carry), is `domain-error`; a non-numeric, non-temporal operand where a number was required is `wrong-type`; any operand that is itself indeterminate makes the whole node indeterminate, with no rescuing value on the other side (see [Three-valued propagation rules](#three-valued-propagation-rules)).
490
508
 
491
509
  ### `call`
492
510
 
493
- A named function applied to an ordered list of `ExpressionNode` arguments. The set of named functions is intentionally open-ended and resolved through a function registry supplied at evaluator construction time — `minimum`, `maximum`, `absoluteValue`, `round`, `squareRoot`, and `logarithm` are starting examples, not an exhaustive list; new functions are added to the registry as concrete need arises. Calling an unregistered function name is `wrong-type` ("no function registered under this name"); calling a registered function with an argument outside its domain (e.g. `squareRoot` given a negative number) is `domain-error`.
511
+ A named function applied to an ordered list of `ExpressionNode` arguments. The set of named functions is intentionally open-ended and resolved through a function registry supplied at evaluator construction time — `minimum`, `maximum`, `absoluteValue`, `round`, `squareRoot`, `exponential`, and `logarithm` are starting examples, not an exhaustive list (the ones the [command line](#command-line) offers are exported as `builtinFunctions`); new functions are added to the registry as concrete need arises. Calling an unregistered function name is `wrong-type` ("no function registered under this name"); calling a registered function with an argument outside its domain (e.g. `squareRoot` given a negative number) is `domain-error`.
494
512
 
495
513
  ### Units
496
514
 
@@ -506,7 +524,7 @@ A named function applied to an ordered list of `ExpressionNode` arguments. The s
506
524
  - `instant − instant → duration`
507
525
  - `instant + duration → instant` (and `duration + instant → instant`)
508
526
 
509
- Any other arithmetic combination touching an `instant` or `duration` (adding two instants, multiplying a duration by an instant, comparing an instant against a plain number, and so on) is `wrong-type`. A reference implementation normalises `duration` values to a single base unit (milliseconds) internally before combining two durations of different `DurationUnit`s, then reports the result in whichever unit the node's own context calls for.
527
+ Any other arithmetic combination touching an `instant` or `duration` (adding two instants, multiplying a duration by an instant, comparing an instant against a plain number, and so on) is `wrong-type`. A reference implementation normalises `duration` values to a single base unit (milliseconds) internally before combining two durations of different `DurationUnit`s, then reports the result in whichever unit the node's own context calls for. Comparing two durations (`compare`, `memberOf`) is exact for any two finite durations in any units, and does not convert to milliseconds: it divides the finer one down into the coarser unit, which cannot overflow, and when the two rounded values come out equal it settles the tie exactly from the numbers' binary expansions.
510
528
 
511
529
  ### Complex values
512
530
 
@@ -525,8 +543,8 @@ The magnitude-and-phase view stays reachable through four exported conversion he
525
543
  **Arithmetic.**
526
544
 
527
545
  - `add`/`subtract` are component-wise, requiring **identical** dimensional-exponent maps exactly as real numbers do (see [Units](#units)).
528
- - `multiply`/`divide` are real complex multiplication and division — `(a + bi)(c + di) = (ac − bd) + (ad + bc)i`, and the corresponding quotient — never component-wise. Units combine by the same dimensional analysis real numbers use. A zero divisor means both components zero; a divisor with only a zero real part divides perfectly well.
529
- - `power` is defined for a **real integer exponent** and evaluated as the repeated multiplication that integer exponentiation is, with a negative exponent the reciprocal of the positive one. Like a real `power`, it requires dimensionless operands. An arbitrary complex exponent is a genuinely bigger question — it needs the complex logarithm, which is multivalued, so it needs a branch-cut convention this design has not chosen — and is deliberately out of scope for now: it is `wrong-type`, as is a non-integer real exponent, on the same reading of that code used throughout ("an answer exists, but this operator does not accept this operand" — compare `power`'s existing dimensionless-operands requirement, also `wrong-type`).
546
+ - `multiply`/`divide` are real complex multiplication and division — `(a + bi)(c + di) = (ac − bd) + (ad + bc)i`, and the corresponding quotient — never component-wise. The divisor and the dividend are each scaled by their own power of two, which brings the larger component of each to about a quarter, the quotient is computed on those scaled values, and the combined power of two is applied to the result once. Where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4); where it is subnormal the result is within a few spacings of the true value (under 5 measured), not correctly rounded. A quotient too large for a double is `domain-error`, and one below about half the smallest subnormal is zero; both thresholds are fuzzy by that error near the edge (measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was refused). A zero dividend gives zero without preserving the signs of its zeros, which is visible only through `Object.is` on the library function, not through JSON, `compare` or `memberOf`. Units combine by the same dimensional analysis real numbers use. A zero divisor means both components zero; a divisor with only a zero real part divides perfectly well.
547
+ - `power` is defined for a **real integer exponent** and evaluated as the repeated multiplication that integer exponentiation is, grouped by squaring so the work grows with the logarithm of the exponent. The price is accuracy: the error of squaring grows in proportion to |n|, so for large exponents the result is many times less accurate than a plain multiplication loop's. These are observations from samples, not bounds, and the figures move from sample to sample. Against a 140-digit reference on random unit-magnitude bases, the mean error of squaring was between 15 and 56 times a plain loop's for |n| from 1e3 to 1e7, growing by about a factor of ten per tenfold increase in |n| (roughly 0.23 |n| units of 2^-53). For |n| up to 24 the worst error was about 20 units of 2^-53: 18.5 for positive and 18.2 for negative exponents over 50,000 bases per exponent, and up to 19.7 in another sample of 40,000. A negative exponent is the reciprocal of the positive power, except where that power overflows or underflows, when the reciprocal is raised instead so a representable result is not lost. Like a real `power`, it requires dimensionless operands. An arbitrary complex exponent is a genuinely bigger question — it needs the complex logarithm, which is multivalued, so it needs a branch-cut convention this design has not chosen — and is deliberately out of scope for now: it is `wrong-type`, as is a non-integer real exponent, on the same reading of that code used throughout ("an answer exists, but this operator does not accept this operand" — compare `power`'s existing dimensionless-operands requirement, also `wrong-type`).
530
548
  - `modulo` is `domain-error`, not `wrong-type`: a remainder needs a canonical notion of how many whole divisors fit, and the complex plane has no ordering to supply one. There is no answer to accept, which is the same category as division by zero.
531
549
 
532
550
  **A real operand is promoted, never rejected.** Mixing a `number` with a `complex` in one `arithmetic` node works: every real number *is* a complex number with a zero imaginary part, so the promotion is exact, total, and canonical — unlike the temporal cross-kind combinations above, which had to be enumerated one by one precisely because no such embedding exists between an `instant` and a `duration`. Scaling a complex value by a real one, or offsetting it by a real constant, is the common case, and forcing every real literal in such a formula to be rewritten as a complex one would defeat the point. The result is `complex` whenever either operand is, even when the imaginary part comes out zero: a node's result kind follows its operand kinds, never the values that happen to flow through it.
@@ -540,7 +558,7 @@ const functions: FunctionRegistry = {
540
558
  magnitude: (args) =>
541
559
  args[0]?.kind === "complex"
542
560
  ? complexMagnitude(args[0])
543
- : { domainError: "expected a complex argument" },
561
+ : { wrongType: "expected a complex argument" },
544
562
  };
545
563
  ```
546
564
 
@@ -794,23 +812,25 @@ Both are exported directly, bound to an empty function registry — under them,
794
812
  ```ts
795
813
  type FunctionRegistry = Record<
796
814
  string,
797
- (args: readonly ComputedValue[]) => ComputedValue | { domainError: string }
815
+ (args: readonly ComputedValue[]) => ComputedValue | FunctionFailure
798
816
  >;
799
817
 
818
+ type FunctionFailure = { domainError: string } | { wrongType: string };
819
+
800
820
  function createEvaluator(options: { functions?: FunctionRegistry }): {
801
821
  evaluatePredicate: (node: PredicateNode, context: EvaluationContext, resolvers: Resolvers) => Promise<Evaluation<boolean>>;
802
822
  evaluateValue: (node: ExpressionNode, context: EvaluationContext, resolvers: Resolvers) => Promise<Evaluation<ComputedValue>>;
803
823
  };
804
824
  ```
805
825
 
806
- A registered function signals an argument outside its domain by *returning* `{ domainError: message }` rather than throwing, which is what keeps `call` inside the same three-outcome model as every other node kind (see [The evaluation model](#the-evaluation-model)); only the registry's own keys count as registered names, so a tree naming an inherited `Object.prototype` member is `wrong-type` like any other unregistered name.
826
+ A registered function signals a failure by *returning* a `FunctionFailure` rather than throwing, which is what keeps `call` inside the same three-outcome model as every other node kind (see [The evaluation model](#the-evaluation-model)): `{ domainError: message }` for an argument of an acceptable kind outside the function's domain (`domain-error`), `{ wrongType: message }` for an argument the function cannot accept at all, such as the wrong kind or units that do not match (`wrong-type`). Only the registry's own keys count as registered names, so a tree naming an inherited `Object.prototype` member is `wrong-type` like any other unregistered name.
807
827
 
808
828
  ```ts
809
829
  const { evaluateValue } = createEvaluator({
810
830
  functions: {
811
831
  squareRoot: (args) => {
812
832
  const [arg] = args;
813
- if (arg?.kind !== "number") return { domainError: "squareRoot requires one number argument" };
833
+ if (arg?.kind !== "number") return { wrongType: "squareRoot requires one number argument" };
814
834
  if (arg.value < 0) return { domainError: "squareRoot of a negative number is not a real number" };
815
835
  return { kind: "number", value: Math.sqrt(arg.value) };
816
836
  },
@@ -848,9 +868,9 @@ How each reason category can arise, per node kind. "Propagates" means: an indete
848
868
  | `some` / `every` | an item's `filter` or `item` sub-node reports not-found, and it is not absorbed by an already-decided item | as `not-found` | as `not-found` |
849
869
  | literals (`numberLiteral`, `textLiteral`, `instantLiteral`, `durationLiteral`, `complexLiteral`) | never | never | never |
850
870
  | `reference` | resolver reports absence | resolver's value doesn't match an expected `unit`, or is used where an incompatible kind is required upstream | never directly |
851
- | `arithmetic` | either operand not found | operand not numeric (or temporal-kind mismatch — see [Temporal values](#temporal-values)), or unit mismatch on add/subtract, or a `power` exponent that is not a real integer over a `complex` operand (see [Complex values](#complex-values)) | zero divisor, `modulo` over a `complex` operand, or any other documented domain violation for the operator |
871
+ | `arithmetic` | either operand not found | operand not numeric (or temporal-kind mismatch — see [Temporal values](#temporal-values)), or unit mismatch on add/subtract, or a `power` exponent that is not a real integer over a `complex` operand (see [Complex values](#complex-values)) | zero divisor, `modulo` over a `complex` operand, a result that overflows the finite range, or any other documented domain violation for the operator |
852
872
  | `negate` | operand not found | operand not `number`/`duration`/`complex` | never directly |
853
- | `call` | any argument not found | unregistered function name, or an argument of the wrong kind for that function | argument outside the function's valid domain (e.g. negative input to `squareRoot`) |
873
+ | `call` | any argument not found | unregistered function name, or an argument the function cannot accept (the wrong kind, or mismatched units) | argument outside the function's valid domain (e.g. negative input to `squareRoot`) |
854
874
  | `lookup` | any key not found, or resolver reports no match | a key expression resolves to the wrong kind for that table | never directly |
855
875
  | `conditional` | `"first"`: an unmatched guard's own evaluation is `not-found`, before any earlier guard matched.<br>`"unique"`: any case's `when` is `not-found`, unless 2+ cases already definitely matched (see `domain-error`, which then takes priority).<br>Both: also the chosen branch's (`then`/`fallback`) own result if it is `not-found`. | Same pattern as `not-found`, substituting `wrong-type` throughout (guard evaluation and chosen branch alike). | `"unique"` only: 2+ cases are definitely `true` — see [`conditional`](#conditional)'s absorption order.<br>Both: same pattern as `not-found`, substituting `domain-error` (guard evaluation and chosen branch alike). |
856
876
  | `fold` | any participating item's `filter`, `item`, or `combine` evaluation is `not-found`; or a `reduce`'s `initial` is `not-found` | any participating item's `filter`, `item`, or `combine` evaluation is `wrong-type`; or a `reduce`'s `initial` is `wrong-type` | empty (post-filter) collection with `max`/`min` (no first item to seed from); or any participating item's `item`/`combine` evaluation is `domain-error`; or a `reduce`'s `initial` is `domain-error` |
@@ -0,0 +1,129 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_computed_value = require("./computed-value.cjs");
3
+ //#region src/builtin-functions.ts
4
+ const DECIMAL_BASE = 10;
5
+ const BINARY_BASE = 2;
6
+ /** Beyond this many decimal places a double either has no digit left to round (positive places) or rounds to zero (negative places): the decimal exponent range of a finite double, from the largest value's order of magnitude down to the smallest subnormal's. Clamping to it keeps the exponent written into a number string well formed whatever count a caller passes. */
7
+ const DECIMAL_PLACES_LIMIT = Math.ceil(Math.log10(Number.MAX_VALUE) - Math.log10(Number.MIN_VALUE));
8
+ function isNumberValue(value) {
9
+ return value?.kind === "number";
10
+ }
11
+ function isDimensionless(value) {
12
+ return require_computed_value.unitsEqual(value.unit, void 0);
13
+ }
14
+ /** The magnitude of a number that carries no unit, or `undefined` for any other value. */
15
+ function dimensionlessNumber(value) {
16
+ return isNumberValue(value) && isDimensionless(value) ? value.value : void 0;
17
+ }
18
+ function withUnit(value, unit) {
19
+ return unit === void 0 ? {
20
+ kind: "number",
21
+ value
22
+ } : {
23
+ kind: "number",
24
+ value,
25
+ unit
26
+ };
27
+ }
28
+ /** The one exit for every numeric result: a value that left the finite range (an overflow or a limit) would otherwise surface as `Infinity` or `NaN` inside a definite value, which JSON writes as `null`. */
29
+ function finiteNumber(name, value, unit) {
30
+ return Number.isFinite(value) ? withUnit(value, unit) : { domainError: `${name} produced a result that is not a finite number` };
31
+ }
32
+ function singleNumber(name, args) {
33
+ const [arg] = args;
34
+ if (args.length !== 1 || !isNumberValue(arg)) return { wrongType: `${name} requires exactly one number argument` };
35
+ return arg;
36
+ }
37
+ /** Halves every dimension's exponent, or `false` when one is odd and the root would need a fractional exponent. */
38
+ function halveUnit(unit) {
39
+ if (unit === void 0) return void 0;
40
+ const halved = {};
41
+ for (const [dimension, exponent] of Object.entries(unit)) {
42
+ if (exponent === 0) continue;
43
+ if (exponent % 2 !== 0) return false;
44
+ halved[dimension] = exponent / 2;
45
+ }
46
+ return halved;
47
+ }
48
+ function extremum(name, args, prefer) {
49
+ const [first, ...rest] = args;
50
+ if (!isNumberValue(first)) return { wrongType: `${name} requires at least one number argument` };
51
+ let best = first;
52
+ for (const arg of rest) {
53
+ if (!isNumberValue(arg)) return { wrongType: `${name} requires number arguments only` };
54
+ if (!require_computed_value.unitsEqual(arg.unit, first.unit)) return { wrongType: `${name} requires arguments in the same unit` };
55
+ if (prefer(arg.value, best.value)) best = arg;
56
+ }
57
+ return finiteNumber(name, best.value, best.unit);
58
+ }
59
+ /** Moves the decimal point of a number by editing the exponent of its shortest decimal form, so `1.005` shifted by 2 places is parsed from the text `1.005e2` (exactly 100.5) rather than computed as `1.005 * 100` (100.49999999999999). `String` writes a large or small value in exponent form already (`1.5e-7`), so the existing exponent is read and added to rather than appended to. */
60
+ function shiftDecimalPoint(value, places) {
61
+ const text = String(value);
62
+ const marker = text.indexOf("e");
63
+ const mantissa = marker === -1 ? text : text.slice(0, marker);
64
+ const exponent = marker === -1 ? 0 : Number(text.slice(marker + 1));
65
+ return Number(`${mantissa}e${String(exponent + places)}`);
66
+ }
67
+ /** Rounds to `places` decimal places, halves away from zero, working on the decimal number the value is written as. A value whose shifted magnitude reaches the largest safe integer has no fractional digit at that precision (or shifts out of the finite range altogether), so it is returned as it is. */
68
+ function roundHalfAwayFromZero(value, places) {
69
+ const clamped = Math.max(-DECIMAL_PLACES_LIMIT, Math.min(DECIMAL_PLACES_LIMIT, places));
70
+ const shifted = shiftDecimalPoint(Math.abs(value), clamped);
71
+ if (!(shifted < Number.MAX_SAFE_INTEGER)) return value;
72
+ const rounded = shiftDecimalPoint(Math.round(shifted), -clamped);
73
+ return rounded === 0 ? 0 : Math.sign(value) * rounded;
74
+ }
75
+ /**
76
+ * The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, and `logarithm` (natural, or to an optional base). They take real numbers only: a complex value is refused by every one of them, `absoluteValue` included.
77
+ *
78
+ * Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
79
+ *
80
+ * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `round` keep the argument's unit (and the first two require all arguments to share one); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
81
+ *
82
+ * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
83
+ */
84
+ const builtinFunctions = Object.freeze({
85
+ minimum: (args) => extremum("minimum", args, (candidate, best) => candidate < best),
86
+ maximum: (args) => extremum("maximum", args, (candidate, best) => candidate > best),
87
+ absoluteValue: (args) => {
88
+ const arg = singleNumber("absoluteValue", args);
89
+ if ("wrongType" in arg) return arg;
90
+ return finiteNumber("absoluteValue", Math.abs(arg.value), arg.unit);
91
+ },
92
+ round: (args) => {
93
+ const [value, places, ...extra] = args;
94
+ if (!isNumberValue(value) || extra.length > 0) return { wrongType: "round requires a number and an optional count of decimal places" };
95
+ if (places === void 0) return finiteNumber("round", roundHalfAwayFromZero(value.value, 0), value.unit);
96
+ if (!isNumberValue(places) || !isDimensionless(places)) return { wrongType: "round requires its decimal places to be a dimensionless number" };
97
+ if (!Number.isInteger(places.value)) return { domainError: "round requires its decimal places to be an integer" };
98
+ return finiteNumber("round", roundHalfAwayFromZero(value.value, places.value), value.unit);
99
+ },
100
+ squareRoot: (args) => {
101
+ const arg = singleNumber("squareRoot", args);
102
+ if ("wrongType" in arg) return arg;
103
+ const unit = halveUnit(arg.unit);
104
+ if (unit === false) return { wrongType: "squareRoot requires every unit exponent to be even" };
105
+ if (arg.value < 0) return { domainError: "squareRoot of a negative number is not a real number" };
106
+ return finiteNumber("squareRoot", Math.sqrt(arg.value), unit);
107
+ },
108
+ exponential: (args) => {
109
+ const arg = singleNumber("exponential", args);
110
+ if ("wrongType" in arg) return arg;
111
+ if (!isDimensionless(arg)) return { wrongType: "exponential requires a dimensionless number" };
112
+ return finiteNumber("exponential", Math.exp(arg.value));
113
+ },
114
+ logarithm: (args) => {
115
+ const [value, base, ...extra] = args;
116
+ if (!isNumberValue(value) || extra.length > 0) return { wrongType: "logarithm requires a number and an optional base" };
117
+ if (!isDimensionless(value)) return { wrongType: "logarithm requires a dimensionless number" };
118
+ const baseNumber = base === void 0 ? void 0 : dimensionlessNumber(base);
119
+ if (base !== void 0 && baseNumber === void 0) return { wrongType: "logarithm requires its base to be a dimensionless number" };
120
+ if (value.value <= 0) return { domainError: "logarithm requires a number above zero" };
121
+ if (baseNumber === void 0) return finiteNumber("logarithm", Math.log(value.value));
122
+ if (baseNumber <= 0 || baseNumber === 1) return { domainError: "logarithm requires its base to be above zero and not one" };
123
+ if (baseNumber === DECIMAL_BASE) return finiteNumber("logarithm", Math.log10(value.value));
124
+ if (baseNumber === BINARY_BASE) return finiteNumber("logarithm", Math.log2(value.value));
125
+ return finiteNumber("logarithm", Math.log(value.value) / Math.log(baseNumber));
126
+ }
127
+ });
128
+ //#endregion
129
+ exports.builtinFunctions = builtinFunctions;
@@ -0,0 +1,13 @@
1
+ import { FunctionRegistry } from "./functions.cjs";
2
+ //#region src/builtin-functions.d.ts
3
+ /**
4
+ * The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, and `logarithm` (natural, or to an optional base). They take real numbers only: a complex value is refused by every one of them, `absoluteValue` included.
5
+ *
6
+ * Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
7
+ *
8
+ * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `round` keep the argument's unit (and the first two require all arguments to share one); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
9
+ *
10
+ * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
11
+ */
12
+ export declare const builtinFunctions: FunctionRegistry;
13
+ //#endregion
@@ -0,0 +1,13 @@
1
+ import { FunctionRegistry } from "./functions.js";
2
+ //#region src/builtin-functions.d.ts
3
+ /**
4
+ * The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, and `logarithm` (natural, or to an optional base). They take real numbers only: a complex value is refused by every one of them, `absoluteValue` included.
5
+ *
6
+ * Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
7
+ *
8
+ * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `round` keep the argument's unit (and the first two require all arguments to share one); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
9
+ *
10
+ * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
11
+ */
12
+ export declare const builtinFunctions: FunctionRegistry;
13
+ //#endregion
@@ -0,0 +1,128 @@
1
+ import { unitsEqual } from "./computed-value.js";
2
+ //#region src/builtin-functions.ts
3
+ const DECIMAL_BASE = 10;
4
+ const BINARY_BASE = 2;
5
+ /** Beyond this many decimal places a double either has no digit left to round (positive places) or rounds to zero (negative places): the decimal exponent range of a finite double, from the largest value's order of magnitude down to the smallest subnormal's. Clamping to it keeps the exponent written into a number string well formed whatever count a caller passes. */
6
+ const DECIMAL_PLACES_LIMIT = Math.ceil(Math.log10(Number.MAX_VALUE) - Math.log10(Number.MIN_VALUE));
7
+ function isNumberValue(value) {
8
+ return value?.kind === "number";
9
+ }
10
+ function isDimensionless(value) {
11
+ return unitsEqual(value.unit, void 0);
12
+ }
13
+ /** The magnitude of a number that carries no unit, or `undefined` for any other value. */
14
+ function dimensionlessNumber(value) {
15
+ return isNumberValue(value) && isDimensionless(value) ? value.value : void 0;
16
+ }
17
+ function withUnit(value, unit) {
18
+ return unit === void 0 ? {
19
+ kind: "number",
20
+ value
21
+ } : {
22
+ kind: "number",
23
+ value,
24
+ unit
25
+ };
26
+ }
27
+ /** The one exit for every numeric result: a value that left the finite range (an overflow or a limit) would otherwise surface as `Infinity` or `NaN` inside a definite value, which JSON writes as `null`. */
28
+ function finiteNumber(name, value, unit) {
29
+ return Number.isFinite(value) ? withUnit(value, unit) : { domainError: `${name} produced a result that is not a finite number` };
30
+ }
31
+ function singleNumber(name, args) {
32
+ const [arg] = args;
33
+ if (args.length !== 1 || !isNumberValue(arg)) return { wrongType: `${name} requires exactly one number argument` };
34
+ return arg;
35
+ }
36
+ /** Halves every dimension's exponent, or `false` when one is odd and the root would need a fractional exponent. */
37
+ function halveUnit(unit) {
38
+ if (unit === void 0) return void 0;
39
+ const halved = {};
40
+ for (const [dimension, exponent] of Object.entries(unit)) {
41
+ if (exponent === 0) continue;
42
+ if (exponent % 2 !== 0) return false;
43
+ halved[dimension] = exponent / 2;
44
+ }
45
+ return halved;
46
+ }
47
+ function extremum(name, args, prefer) {
48
+ const [first, ...rest] = args;
49
+ if (!isNumberValue(first)) return { wrongType: `${name} requires at least one number argument` };
50
+ let best = first;
51
+ for (const arg of rest) {
52
+ if (!isNumberValue(arg)) return { wrongType: `${name} requires number arguments only` };
53
+ if (!unitsEqual(arg.unit, first.unit)) return { wrongType: `${name} requires arguments in the same unit` };
54
+ if (prefer(arg.value, best.value)) best = arg;
55
+ }
56
+ return finiteNumber(name, best.value, best.unit);
57
+ }
58
+ /** Moves the decimal point of a number by editing the exponent of its shortest decimal form, so `1.005` shifted by 2 places is parsed from the text `1.005e2` (exactly 100.5) rather than computed as `1.005 * 100` (100.49999999999999). `String` writes a large or small value in exponent form already (`1.5e-7`), so the existing exponent is read and added to rather than appended to. */
59
+ function shiftDecimalPoint(value, places) {
60
+ const text = String(value);
61
+ const marker = text.indexOf("e");
62
+ const mantissa = marker === -1 ? text : text.slice(0, marker);
63
+ const exponent = marker === -1 ? 0 : Number(text.slice(marker + 1));
64
+ return Number(`${mantissa}e${String(exponent + places)}`);
65
+ }
66
+ /** Rounds to `places` decimal places, halves away from zero, working on the decimal number the value is written as. A value whose shifted magnitude reaches the largest safe integer has no fractional digit at that precision (or shifts out of the finite range altogether), so it is returned as it is. */
67
+ function roundHalfAwayFromZero(value, places) {
68
+ const clamped = Math.max(-DECIMAL_PLACES_LIMIT, Math.min(DECIMAL_PLACES_LIMIT, places));
69
+ const shifted = shiftDecimalPoint(Math.abs(value), clamped);
70
+ if (!(shifted < Number.MAX_SAFE_INTEGER)) return value;
71
+ const rounded = shiftDecimalPoint(Math.round(shifted), -clamped);
72
+ return rounded === 0 ? 0 : Math.sign(value) * rounded;
73
+ }
74
+ /**
75
+ * The numeric functions a `call` node can name when an embedder has no registry of its own: `minimum` and `maximum` (one or more numbers in a shared unit), `absoluteValue`, `round` (half away from zero, with an optional count of decimal places), `squareRoot`, `exponential`, and `logarithm` (natural, or to an optional base). They take real numbers only: a complex value is refused by every one of them, `absoluteValue` included.
76
+ *
77
+ * Failures split as the evaluator's own operators split. An argument a function cannot accept at all (the wrong kind, the wrong count, or units that do not fit) is a `wrongType`; an argument of the right kind outside the function's domain (a negative `squareRoot`, a `logarithm` of zero, a base of one, a fractional count of decimal places) or a result that is not a finite number is a `domainError`.
78
+ *
79
+ * Units follow the evaluator's rule that dimensions are never silently converted. `minimum`, `maximum`, `absoluteValue` and `round` keep the argument's unit (and the first two require all arguments to share one); `squareRoot` halves each dimension's exponent and refuses a unit whose exponents are not all even; `exponential` and `logarithm` accept only dimensionless numbers and return one.
80
+ *
81
+ * Frozen, so mutating the export cannot change what `evaluateDocument` resolves.
82
+ */
83
+ const builtinFunctions = Object.freeze({
84
+ minimum: (args) => extremum("minimum", args, (candidate, best) => candidate < best),
85
+ maximum: (args) => extremum("maximum", args, (candidate, best) => candidate > best),
86
+ absoluteValue: (args) => {
87
+ const arg = singleNumber("absoluteValue", args);
88
+ if ("wrongType" in arg) return arg;
89
+ return finiteNumber("absoluteValue", Math.abs(arg.value), arg.unit);
90
+ },
91
+ round: (args) => {
92
+ const [value, places, ...extra] = args;
93
+ if (!isNumberValue(value) || extra.length > 0) return { wrongType: "round requires a number and an optional count of decimal places" };
94
+ if (places === void 0) return finiteNumber("round", roundHalfAwayFromZero(value.value, 0), value.unit);
95
+ if (!isNumberValue(places) || !isDimensionless(places)) return { wrongType: "round requires its decimal places to be a dimensionless number" };
96
+ if (!Number.isInteger(places.value)) return { domainError: "round requires its decimal places to be an integer" };
97
+ return finiteNumber("round", roundHalfAwayFromZero(value.value, places.value), value.unit);
98
+ },
99
+ squareRoot: (args) => {
100
+ const arg = singleNumber("squareRoot", args);
101
+ if ("wrongType" in arg) return arg;
102
+ const unit = halveUnit(arg.unit);
103
+ if (unit === false) return { wrongType: "squareRoot requires every unit exponent to be even" };
104
+ if (arg.value < 0) return { domainError: "squareRoot of a negative number is not a real number" };
105
+ return finiteNumber("squareRoot", Math.sqrt(arg.value), unit);
106
+ },
107
+ exponential: (args) => {
108
+ const arg = singleNumber("exponential", args);
109
+ if ("wrongType" in arg) return arg;
110
+ if (!isDimensionless(arg)) return { wrongType: "exponential requires a dimensionless number" };
111
+ return finiteNumber("exponential", Math.exp(arg.value));
112
+ },
113
+ logarithm: (args) => {
114
+ const [value, base, ...extra] = args;
115
+ if (!isNumberValue(value) || extra.length > 0) return { wrongType: "logarithm requires a number and an optional base" };
116
+ if (!isDimensionless(value)) return { wrongType: "logarithm requires a dimensionless number" };
117
+ const baseNumber = base === void 0 ? void 0 : dimensionlessNumber(base);
118
+ if (base !== void 0 && baseNumber === void 0) return { wrongType: "logarithm requires its base to be a dimensionless number" };
119
+ if (value.value <= 0) return { domainError: "logarithm requires a number above zero" };
120
+ if (baseNumber === void 0) return finiteNumber("logarithm", Math.log(value.value));
121
+ if (baseNumber <= 0 || baseNumber === 1) return { domainError: "logarithm requires its base to be above zero and not one" };
122
+ if (baseNumber === DECIMAL_BASE) return finiteNumber("logarithm", Math.log10(value.value));
123
+ if (baseNumber === BINARY_BASE) return finiteNumber("logarithm", Math.log2(value.value));
124
+ return finiteNumber("logarithm", Math.log(value.value) / Math.log(baseNumber));
125
+ }
126
+ });
127
+ //#endregion
128
+ export { builtinFunctions };
@@ -0,0 +1,48 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region src/complex-division.ts
3
+ /**
4
+ * `value * 2 ** exponent`, applied in two halves because `2 ** exponent` is infinite beyond 1023 and a quotient can need a shift of about twice that. A power of two multiplies a double exactly while the result stays normal, so when the result can be non-zero and finite (a shift between about -1077 and 1024 for a scaled quotient of order one) each half is at most about 540 in magnitude, the first multiplication is exact, and the second rounds only where the result is subnormal. Outside that range the result overflows or is below the smallest subnormal: a non-zero value gives an infinity or zero, which is correct, and a zero value with a shift of 2047 or more gives NaN (zero times an infinite half), which the caller's finite check treats as it does an infinity.
5
+ */
6
+ function scaleByPowerOfTwo(value, exponent) {
7
+ const firstHalf = Math.trunc(exponent / 2);
8
+ return value * 2 ** firstHalf * 2 ** (exponent - firstHalf);
9
+ }
10
+ /** The exponent of the power of two that brings a magnitude to between a quarter and a half, which this file calls about a quarter. `Math.log2` is rounded, so for a magnitude just under a power of two it can return that power itself and the result lands just under a quarter instead. The magnitude must be non-zero. */
11
+ function scaleToAboutAQuarter(larger) {
12
+ return -Math.floor(Math.log2(larger)) - 2;
13
+ }
14
+ /**
15
+ * The components of `dividend / divisor` for a non-zero divisor.
16
+ *
17
+ * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
18
+ *
19
+ * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
20
+ *
21
+ * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
22
+ *
23
+ * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
24
+ *
25
+ * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
26
+ */
27
+ function divideComplexComponents(dividend, divisor) {
28
+ const largerDividend = Math.max(Math.abs(dividend.re), Math.abs(dividend.im));
29
+ if (largerDividend === 0) return {
30
+ re: 0,
31
+ im: 0
32
+ };
33
+ const largerDivisor = Math.max(Math.abs(divisor.re), Math.abs(divisor.im));
34
+ const dividendScale = scaleToAboutAQuarter(largerDividend);
35
+ const divisorScale = scaleToAboutAQuarter(largerDivisor);
36
+ const a = scaleByPowerOfTwo(dividend.re, dividendScale);
37
+ const b = scaleByPowerOfTwo(dividend.im, dividendScale);
38
+ const c = scaleByPowerOfTwo(divisor.re, divisorScale);
39
+ const d = scaleByPowerOfTwo(divisor.im, divisorScale);
40
+ const denominator = c * c + d * d;
41
+ const shift = divisorScale - dividendScale;
42
+ return {
43
+ re: scaleByPowerOfTwo((a * c + b * d) / denominator, shift),
44
+ im: scaleByPowerOfTwo((b * c - a * d) / denominator, shift)
45
+ };
46
+ }
47
+ //#endregion
48
+ exports.divideComplexComponents = divideComplexComponents;
@@ -0,0 +1,25 @@
1
+ //#region src/complex-division.d.ts
2
+ /**
3
+ * The components of `dividend / divisor` for a non-zero divisor.
4
+ *
5
+ * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
6
+ *
7
+ * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
8
+ *
9
+ * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
10
+ *
11
+ * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
12
+ *
13
+ * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
14
+ */
15
+ export declare function divideComplexComponents(dividend: Readonly<{
16
+ re: number;
17
+ im: number;
18
+ }>, divisor: Readonly<{
19
+ re: number;
20
+ im: number;
21
+ }>): {
22
+ re: number;
23
+ im: number;
24
+ };
25
+ //#endregion
@@ -0,0 +1,25 @@
1
+ //#region src/complex-division.d.ts
2
+ /**
3
+ * The components of `dividend / divisor` for a non-zero divisor.
4
+ *
5
+ * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
6
+ *
7
+ * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
8
+ *
9
+ * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
10
+ *
11
+ * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
12
+ *
13
+ * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
14
+ */
15
+ export declare function divideComplexComponents(dividend: Readonly<{
16
+ re: number;
17
+ im: number;
18
+ }>, divisor: Readonly<{
19
+ re: number;
20
+ im: number;
21
+ }>): {
22
+ re: number;
23
+ im: number;
24
+ };
25
+ //#endregion
@@ -0,0 +1,47 @@
1
+ //#region src/complex-division.ts
2
+ /**
3
+ * `value * 2 ** exponent`, applied in two halves because `2 ** exponent` is infinite beyond 1023 and a quotient can need a shift of about twice that. A power of two multiplies a double exactly while the result stays normal, so when the result can be non-zero and finite (a shift between about -1077 and 1024 for a scaled quotient of order one) each half is at most about 540 in magnitude, the first multiplication is exact, and the second rounds only where the result is subnormal. Outside that range the result overflows or is below the smallest subnormal: a non-zero value gives an infinity or zero, which is correct, and a zero value with a shift of 2047 or more gives NaN (zero times an infinite half), which the caller's finite check treats as it does an infinity.
4
+ */
5
+ function scaleByPowerOfTwo(value, exponent) {
6
+ const firstHalf = Math.trunc(exponent / 2);
7
+ return value * 2 ** firstHalf * 2 ** (exponent - firstHalf);
8
+ }
9
+ /** The exponent of the power of two that brings a magnitude to between a quarter and a half, which this file calls about a quarter. `Math.log2` is rounded, so for a magnitude just under a power of two it can return that power itself and the result lands just under a quarter instead. The magnitude must be non-zero. */
10
+ function scaleToAboutAQuarter(larger) {
11
+ return -Math.floor(Math.log2(larger)) - 2;
12
+ }
13
+ /**
14
+ * The components of `dividend / divisor` for a non-zero divisor.
15
+ *
16
+ * The textbook route multiplies both sides by the divisor's conjugate and divides by `re^2 + im^2`, which overflows for a divisor near the top of the range and underflows for one near the bottom, even when the quotient is an ordinary number. Smith's algorithm avoids that for ordinary operands but still overflows its denominator or numerator above about 9e307 and loses accuracy for subnormal divisors, giving a wrong finite answer (zero for a quotient of about 0.07) rather than an error.
17
+ *
18
+ * Here the divisor is multiplied by a power of two that brings its larger component to about a quarter, and the dividend by its own power of two that does the same for its larger component. The conjugate formula then runs on those two scaled values. Its largest product is of order one (the two larger components multiplied), so nothing in it overflows, and a product that underflows belongs to a smaller component and is negligible beside the larger terms.
19
+ *
20
+ * The scaled quotient is the true quotient multiplied by `2 ** (dividendScale - divisorScale)`: for a dividend of 8 (scale -5, scaled to 0.25) and a divisor of 1 (scale -2, scaled to 0.25) the scaled quotient is 1, and the true quotient 8 is 1 times `2 ** 3`. The result is therefore the scaled quotient multiplied by `2 ** (divisorScale - dividendScale)`, applied once at the end. For a quotient in the subnormal range that multiplication is the only rounding of the larger components beyond the formula's own few.
21
+ *
22
+ * Accuracy: where the quotient is a normal number the error over the pair is a few units of 2^-53 (the measured worst case over a large exact-rational check is under 4), and a component much smaller than the other is accurate relative to the larger one, not to itself. Where the quotient lies in the subnormal range, results are within a few spacings of the true value (the measured worst case is under 5), not correctly rounded. A quotient too large for a double comes out with a non-finite component (an infinity, or NaN when the other component is zero), left to the caller's finite check; one below about half the smallest subnormal comes out as zero. Both thresholds are fuzzy by that error near the edge: measured, a true quotient up to about 2 ulps above the largest double came back finite, and a representable one a little over 1 ulp below it was reported as an overflow.
23
+ *
24
+ * A zero dividend gives zero in both components without regard to the signs of its zeros, so `-0` is not preserved; that is visible only through `Object.is` on this function's result, not through JSON, `compare` or `memberOf`.
25
+ */
26
+ function divideComplexComponents(dividend, divisor) {
27
+ const largerDividend = Math.max(Math.abs(dividend.re), Math.abs(dividend.im));
28
+ if (largerDividend === 0) return {
29
+ re: 0,
30
+ im: 0
31
+ };
32
+ const largerDivisor = Math.max(Math.abs(divisor.re), Math.abs(divisor.im));
33
+ const dividendScale = scaleToAboutAQuarter(largerDividend);
34
+ const divisorScale = scaleToAboutAQuarter(largerDivisor);
35
+ const a = scaleByPowerOfTwo(dividend.re, dividendScale);
36
+ const b = scaleByPowerOfTwo(dividend.im, dividendScale);
37
+ const c = scaleByPowerOfTwo(divisor.re, divisorScale);
38
+ const d = scaleByPowerOfTwo(divisor.im, divisorScale);
39
+ const denominator = c * c + d * d;
40
+ const shift = divisorScale - dividendScale;
41
+ return {
42
+ re: scaleByPowerOfTwo((a * c + b * d) / denominator, shift),
43
+ im: scaleByPowerOfTwo((b * c - a * d) / denominator, shift)
44
+ };
45
+ }
46
+ //#endregion
47
+ export { divideComplexComponents };