metanum 2.0.3 → 2.1.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.
package/metanum.js CHANGED
@@ -1,5 +1,5 @@
1
- //Author: dlsdl v2.0
2
- //v2.0: Add hyper-root & hyper-log, hardy function, fractional hyperoperation inputs, fix BEAF operation level and format
1
+ //Author: dlsdl v2.1
2
+ //v2.1
3
3
  //Code snippets and templates from OmegaNum.js
4
4
 
5
5
  ;(function (globalScope) {
@@ -228,14 +228,9 @@
228
228
  return Math.log10(Number(str.substring(0, LONG_STRING_MIN_LENGTH))) + (str.length - LONG_STRING_MIN_LENGTH);
229
229
  };
230
230
 
231
- // Canonical form of a value with 0 < |v| < 1: the library stores it as the
232
- // RECIPROCAL with sign 2 (0<v<1) / -2 (-1<v<0) — the same encoding the
233
- // underflow path below already produced, now applied to the WHOLE sub-unit
234
- // range so that `MetaNum(0.5).sign === 2` and every operation result in that
235
- // range carries it too (README: sign 2 / -2 == 0~1 / -1~0).
236
- //
237
- // _skipCanon lets rec() produce the reciprocal of a sub-unit value (2 for 0.5)
238
- // without this rule turning it straight back into a small value.
231
+ // Sub-unit canonical form: 0 < |v| < 1 is stored as the RECIPROCAL with
232
+ // sign 2 / -2 (README: sign 2 / -2 == 0~1 / -1~0). _skipCanon lets rec()
233
+ // produce that reciprocal without this rule turning it back.
239
234
  var _skipCanon = 0;
240
235
  function canonicalizeSubUnit(x) {
241
236
  if (_skipCanon) return x;
@@ -501,35 +496,29 @@
501
496
  return x;
502
497
  };
503
498
 
504
- // Apply the sub-unit canonical form to a public result (constructor input or
505
- // the result of a basic arithmetic op). Deliberately NOT part of normalize():
506
- // normalize runs on every internal intermediate, and the engine's own
507
- // transcendentals (log10 → 0.301, slog, gamma, hyper-op levels) plus hardy's
508
- // coefficient arrays read r0 structurally, so canonicalizing there broke
509
- // them. See canonicalizeSubUnit above.
499
+ // Apply the sub-unit canonical form to a PUBLIC result (constructor input,
500
+ // basic arithmetic). Deliberately not part of normalize(): internal
501
+ // intermediates (transcendentals, slog, gamma, hardy's coefficients) read r0
502
+ // structurally, so canonicalizing there broke them.
510
503
  function canonicalizeResult(x) {
511
504
  if (x instanceof MetaNum) canonicalizeSubUnit(x);
512
505
  return x;
513
506
  }
514
507
 
515
- // Constructor that never applies the sub-unit canonical form. Engine
516
- // internals build values that are consumed STRUCTURALLY (r0 read as a
517
- // magnitude, sign tested for -1): the transcendentals' own results
518
- // (log10(2) = 0.301, slog, gamma, pent_log) and hardy's fractional
519
- // coefficients. Canonicalizing those changed r0[0] from 0.301 to 3.32 and
520
- // silently corrupted every consumer.
508
+ // Constructor that never applies the sub-unit canonical form — for engine
509
+ // internals whose values are consumed STRUCTURALLY (transcendentals' results
510
+ // like log10(2) = 0.301, slog, gamma, pent_log, hardy's fractional
511
+ // coefficients); canonicalizing them turned r0[0] from 0.301 into 3.32.
521
512
  function rawMetaNum(v) {
522
513
  _skipCanon++;
523
514
  try { return new MetaNum(v); } finally { _skipCanon--; }
524
515
  }
525
516
 
526
- // Run fn with the sub-unit canonical form suppressed. Applied to the engine
517
+ // Run fn with the sub-unit canonical form suppressed — for the engine
527
518
  // functions that CONSUME sub-unit magnitudes structurally (gamma's series,
528
- // slog's log10 chain, the layeradd/pentate inverse paths): they read r0 as a
529
- // plain magnitude, so a canonicalized intermediate (log10(2) → r0 [3.32]
530
- // instead of [0.301]) silently produced garbage. The PRODUCERS (log10, ln,
531
- // exp, root, the constructor, add/sub/mul/div) stay canonicalized, so the
532
- // public contract the user asked for still holds.
519
+ // slog's log10 chain, layeradd/pentate inverses): a canonicalized
520
+ // intermediate (log10(2) → r0 [3.32] instead of [0.301]) produced garbage.
521
+ // The PRODUCERS stay canonicalized, so the public contract holds.
533
522
  function rawBody(fn, self, args) {
534
523
  _skipCanon++;
535
524
  try { return fn.apply(self, args || []); } finally { _skipCanon--; }
@@ -626,14 +615,11 @@
626
615
  while (tRows > 1 && isZeroArr(this.array[tRows - 1])) tRows--;
627
616
  while (oRows > 1 && isZeroArr(other.array[oRows - 1])) oRows--;
628
617
 
629
- // Compare ordinal rows (index >= 1) as Cantor normal form. Rows are kept
630
- // sorted by level ascending, so the leading (highest-level) term is last and
631
- // dominates: a single ω-level row (length >= 3, e.g. [1,0,1]) is larger than
632
- // any number of finite-level rows (length 2, e.g. [count, finiteLevel]),
633
- // because 10{ω}10 is infinite while 10{n}10 is finite. Deciding by row count
634
- // alone would wrongly rank 99 finite-level rows above 1 ω-level row, so we
635
- // descend from the top, cancelling equal leading rows, and decide at the
636
- // first row whose level/count differs (cmpArr encodes level then count).
618
+ // Compare ordinal rows (index >= 1) as CNF: rows are sorted by level
619
+ // ascending, so the leading (highest-level) term is last and dominates — one
620
+ // ω-level row ([1,0,1]) beats any number of finite-level rows. Descend from
621
+ // the top, cancel equal leading rows, decide at the first differing
622
+ // level/count (cmpArr encodes level then count).
637
623
  var i = tRows - 1;
638
624
  var j = oRows - 1;
639
625
  while (i >= 1 || j >= 1) {
@@ -960,15 +946,11 @@
960
946
  return x;
961
947
  }
962
948
 
963
- // Like toNumber(), but returns the actual finite JS value for E-notation
964
- // numbers (e.g. 10^16 stored as [[16,1]]) instead of Infinity. This is used
965
- // by hyperoperation functions (expande/multiexpande/powerexpande) to compute
966
- // iteration counts `count = y - 2` when y is a large-but-finite MetaNum.
967
- // toNumber() returns Infinity whenever r0.length > 1 (E-notation) or the
968
- // array has ordinal rows, which is too conservative for count extraction:
969
- // 10^16 is a perfectly finite JS number. We only return Infinity for genuine
970
- // ordinals (layer>0 or array.length>1) or values too large for any JS number
971
- // (tetration+ or 10^(>=309)); the caller falls back to the ordinal branch.
949
+ // Like toNumber(), but returns the finite JS value for E-notation numbers
950
+ // (10^16 = [[16,1]]) instead of Infinity — used to extract iteration counts
951
+ // (count = y-2) in expande/multiexpande/powerexpande. Infinity only for
952
+ // genuine ordinals (layer>0 or array.length>1) or values beyond double range
953
+ // (tetration+, 10^(>=309)); the caller then takes the ordinal branch.
972
954
  function metaFiniteCount(y) {
973
955
  if (y.isNaN()) return NaN;
974
956
  if (y.layer > 0) return Infinity; // ω^ω^... tower
@@ -1247,7 +1229,12 @@
1247
1229
  var powVal = Math.pow(x.toNumber(), other.toNumber());
1248
1230
  if (Number.isFinite(powVal) && Math.abs(powVal) <= MAX_SAFE_INTEGER && powVal !== 0) return new MetaNum(powVal);
1249
1231
  }
1250
- if (x.eq(MetaNum.TEN) && !isSmall(other)) {
1232
+ // 10^e fast path. Only for POSITIVE exponents: `other` stores its
1233
+ // magnitude in r0 with the sign held separately, so a negative exponent
1234
+ // (-324 → array [[324]], sign -1) must NOT be turned into 10^(+324) here.
1235
+ // Negative exponents fall through to the log/normalise path below, which
1236
+ // yields the sub-unit encoding (sign 2 / -2).
1237
+ if (x.eq(MetaNum.TEN) && !isSmall(other) && other.sign === 1) {
1251
1238
  if (other.layer > 0 || other.array.length > 1) return other;
1252
1239
  var newRow0 = other.array[0].slice(0);
1253
1240
  newRow0[1] = (newRow0[1] || 0) + 1;
@@ -1381,6 +1368,14 @@
1381
1368
  var lv = Math.log10(magnitudeOf(this));
1382
1369
  if (Number.isFinite(lv)) return new MetaNum(lv);
1383
1370
  }
1371
+ // Sub-unit E-form: sign 2/-2 with an r0 longer than 1 stores the
1372
+ // RECIPROCAL (e.g. 10^-324 → [[324,1]] sign 2). log10(1/|x|) = -log10(|x|),
1373
+ // and rec() unwraps the reciprocal back to the magnitude. Without this,
1374
+ // log10(10^-324) returned +324, so 10^-324 · 10^324 became 10^648.
1375
+ if (this.sign === 2 &&
1376
+ this.layer === 0 && this.array.length === 1 && this.array[0].length > 1) {
1377
+ return this.rec().log10().neg();
1378
+ }
1384
1379
  if (this.layer === 0 && this.array.length === 1 && this.array[0].length > 1) {
1385
1380
  var r0 = this.array[0];
1386
1381
  if (r0[1] > 0) {
@@ -1956,13 +1951,9 @@
1956
1951
  }
1957
1952
 
1958
1953
  // Fast construction of the diagonal chain D(L) = t{L}t for a plain finite
1959
- // integer base t. The generic successor-rule recursion recomputes the whole
1960
- // chain at every level (each level re-invokes t{n-1}(t)), which is ~O(n^3)
1961
- // for plain diagonals (3{99}3 at maxCols=100 took ~5.5s). Unrolling rule 2
1962
- // once builds the identical normalized array bottom-up:
1963
- // D(1) = t{1}t ; D(n+1) = t{n}^{t-1}(t) = t{n}^{t-2}(D(n))
1964
- // Each t{n}(D(n)) step is the engine's own structured-value fast path, so
1965
- // the result is array-identical to the recursive evaluation, in O(L^2).
1954
+ // integer base t. The generic recursion is ~O(n^3) (3{99}3 took ~5.5s);
1955
+ // unrolling rule 2 once builds the identical array bottom-up in O(L^2):
1956
+ // D(1) = t{1}t ; D(n+1) = t{n}^{t-2}(D(n))
1966
1957
  function canFastDiagonal(t) {
1967
1958
  if (t.layer !== 0 || t.array.length !== 1) return false;
1968
1959
  var n = t.toNumber();
@@ -1995,19 +1986,13 @@
1995
1986
  return r;
1996
1987
  }
1997
1988
 
1998
- // Convert a structured raw-application COUNT C at finite operation level n
1999
- // ({n}^C(10)) to the dlsdl Aa-band smooth argument α (v = 10{n+2}(α)),
2000
- // α ∈ [2,10). A count given canonically as 10{k}(t), t∈[1,10]:
2001
- // t = 10 rewrites exactly to α-anchor 2 one level up (10{k}10=10{k+1}2);
2002
- // each further level promotion is the geometric smooth-log step
2003
- // f → 1 + log10(f) (the same step the low-level polarize produces).
2004
- // Matches dlsdl rule (iii)-(v): {99}^{10{93}10}(10) = 10{101}(2.001607…).
2005
- // Raw application COUNT C at operation level n ({n}^C(10)) -> the dlsdl
2006
- // diagonal-letter smooth argument α in [2,10) with v = 10{n+2}(α).
2007
- // Start from C=10{level}(t) (polarize: a scalar C starts at level 1 with
2008
- // t=log10(C)), then each level promotion is the geometric smooth-log step
2009
- // t → 1+log10(t) (exact t=10 rewrites to the α-anchor 2). The final value
2010
- // lands in [1,2); the diagonal mantissa is α=1+t (2 at the anchor).
1989
+ // Convert a structured raw-application COUNT C at finite level n ({n}^C(10))
1990
+ // to the dlsdl Aa-band smooth argument α (v = 10{n+2}(α)), α ∈ [2,10).
1991
+ // Polarize C to 10{level}(t) (a scalar C starts at level 1, t=log10(C)); each
1992
+ // level promotion is the smooth-log step t → 1+log10(t), and the exact anchor
1993
+ // t=10 rewrites to mantissa 2 one level up (10{k}10 = 10{k+1}2). The final
1994
+ // value lands in [1,2); the mantissa is α = 1+t. Matches dlsdl rule
1995
+ // (iii)-(v): {99}^{10{93}10}(10) = 10{101}(2.001607…).
2011
1996
  function countToDiagonalAlpha(C, n, r0OfC, rowsOfC) {
2012
1997
  var t, level;
2013
1998
  if (r0OfC === undefined || r0OfC === null) {
@@ -2139,12 +2124,10 @@
2139
2124
  return { bottom: b(), repeation: array[ptr][1], arrows: array[ptr][0] };
2140
2125
  }
2141
2126
 
2142
- // Canonical compact form of the smooth diagonal value 10{L}(α) with a
2143
- // NUMERIC α in [1,10): r0=[1] plus one finite row [α, L-1]. The fractional
2144
- // row count survives normalization (only r0 integer columns are floored)
2145
- // and polarize climbs it straight back to t=α at level L-1, so the smooth
2146
- // mantissa is preserved at arbitrary finite levels (used where the iterated
2147
- // arrow loop would MSI-dump the fraction away).
2127
+ // Canonical compact form of the smooth diagonal 10{L}(α), α numeric in
2128
+ // [1,10): r0=[1] plus one finite row [α, L-1]. The fractional row count
2129
+ // survives normalization and polarize climbs it back to t=α at level L-1, so
2130
+ // the smooth mantissa survives at arbitrary finite levels.
2148
2131
  function compactSmoothValue(L, alpha) {
2149
2132
  var m = new MetaNum({ sign: 1, layer: 0, array: [[1], [alpha, L - 1]] });
2150
2133
  return m.normalize();
@@ -2156,13 +2139,10 @@
2156
2139
  arrows = new MetaNum(arrows);
2157
2140
  if (arrows.sign === -1 || arrows.sign === -2) return function () { return MetaNum.NaN.clone(); };
2158
2141
  if (!arrows.isint()) {
2159
- // Fractional hyperoperation level.
2160
- // Geometric interpolation per README rule (i): level n+f acts as the (n+1)-level
2161
- // op on a geometrically interpolated argument — for the canonical
2162
- // diagonal 10{n+f}10 = 10{n+1}(2·5^f). General anchors: θ0 satisfies
2163
- // x{n+1}θ0 = x{n}y (recovered via hyper_log), θ1 = y, θf = θ0·(y/θ0)^f,
2164
- // so x{n+f}y = x{n+1}(θf), continuous in f with
2165
- // x{n}y at f=0 and x{n+1}y at f=1.
2142
+ // Fractional hyperoperation level — geometric interpolation (README
2143
+ // rule (i)): level n+f is the (n+1)-level op on the interpolated argument
2144
+ // θf = θ0·(y/θ0)^f, where θ0 solves x{n+1}θ0 = x{n}y (via hyper_log) and
2145
+ // θ1 = y; the canonical diagonal 10{n+f}10 = 10{n+1}(2·5^f).
2166
2146
  if (arrows.gte(MetaNum.ONE)) {
2167
2147
  var nLev = arrows.floor();
2168
2148
  var frac = arrows.sub(nLev);
@@ -2257,16 +2237,12 @@
2257
2237
  if (alphaC !== null && alphaC >= 2) return compactSmoothValue(arrowsNum + 1, alphaC);
2258
2238
  }
2259
2239
  if (arrowsNum >= MetaNum.maxCols) {
2260
- // Finite arrow level beyond r0 capacity:
2261
- // expand the level chain exactly as far as the array budget allows —
2262
- // r0 filled to maxCols (levels 1..maxCols-1, the top one being the
2263
- // anchor level L-1 col) + [count, level] rows for levels
2264
- // maxCols..L-1 (maxRows-1 rows max; the top level L itself is the
2265
- // 10{L}2 = 10{L-1}10 anchor and takes no row) —
2266
- // and approximate beyond the budget: keep the LARGEST maxRows-1
2267
- // ordinal rows, the ARRAY's second row (first-kept ordinal row) first column +1,
2268
- // first row [10].
2269
- // Swallowing: a finite level sits below any existing ω-level row.
2240
+ // Finite arrow level beyond r0 capacity: expand exactly as far as the
2241
+ // budget allows (r0 to maxCols + [count, level] rows for the rest; the
2242
+ // top level L is the 10{L}2 = 10{L-1}10 anchor and takes no row), then
2243
+ // approximate — keep the LARGEST maxRows-1 rows, bump the first kept
2244
+ // row's count by 1 (truncation marker), base [10]. A finite level sits
2245
+ // below any existing ω-level row (swallowing).
2270
2246
  var j = t.max(other).clone();
2271
2247
  if (j.layer > 0) return j; // ω^ω-tower swallows any finite level
2272
2248
  var idx = -1;
@@ -2303,14 +2279,11 @@
2303
2279
  j.normalize();
2304
2280
  return j;
2305
2281
  }
2306
- // plain finite base: expand the diagonal chain bottom-up.
2307
- // Exact law (matches the engine's own low-level path and the
2308
- // reference): x{L}y = x{L-1}^{y-2}(x{L-1}x), so the top level L-1
2309
- // carries (y-2) ops and every level below — the x{L-1}x tail —
2310
- // carries (x-2) ops:
2311
- // 3{9}3 → 1 op/level, 4{9}4 → 2, 10{25}10 → 8 ops/level (the
2312
- // canonical all-8s form). The top level L itself is the
2313
- // 10{L}2 = 10{L-1}10 anchor and takes no row.
2282
+ // Plain finite base: expand the diagonal chain bottom-up —
2283
+ // x{L}y = x{L-1}^{y-2}(x{L-1}x), so the top level L-1 carries (y-2) ops
2284
+ // and every level below (the x{L-1}x tail) carries (x-2): 3{9}3 → 1
2285
+ // op/level, 10{25}10 → 8 (the canonical all-8s form). The top level L
2286
+ // is the 10{L}2 = 10{L-1}10 anchor and takes no row.
2314
2287
  var subDepth = MetaNum.maxCols - 1;
2315
2288
  var xBase = t.toNumber();
2316
2289
  var yBase = other.toNumber();
@@ -2428,11 +2401,9 @@
2428
2401
  var fastDiag = isFinite(y) && Math.floor(y) === y && canFastDiagonal(t);
2429
2402
  if (arrowsNum >= 23 && y !== Math.floor(y) && Math.floor(y) > 2) {
2430
2403
  // Large integer part with a fractional tail at a high level: the tail
2431
- // would be amplified by the many iterations (e.g. 10{69}69.6 ≈
2432
- // 10{69}10), so use the discrete 10 anchor (accepted convention).
2433
- // y with floor ≤ 2 keeps the smooth fractional path — the recursion
2434
- // bottoms out numerically and carries the smooth Aa-diagonal mantissa
2435
- // (e.g. 10{101}(2.001607)).
2404
+ // would be amplified by the many iterations (10{69}69.6 ≈ 10{69}10), so
2405
+ // use the discrete 10 anchor. y with floor ≤ 2 keeps the smooth path
2406
+ // (carries the Aa-diagonal mantissa, e.g. 10{101}(2.001607)).
2436
2407
  y = 10;
2437
2408
  fastDiag = false;
2438
2409
  }
@@ -2486,14 +2457,11 @@
2486
2457
  };
2487
2458
 
2488
2459
  // ==================== hyper_log / hyper_root ====================
2489
- // Inverses of the hyperoperation a{b}c = d (arrow-style chained API):
2490
- // d.hyper_log(a)(b) = c (recover the right operand / argument)
2491
- // d.hyper_root(c)(b) = a (recover the base / left operand)
2492
- // b = 0 and b = 1 use exact division and logarithms; b ≥ 2 bisects on the
2493
- // monotone arrow engine (issues.md addition 2). Note: for levels b beyond
2494
- // maxCols the forward arrow diagonalizes into one [1|b] marker row and the
2495
- // argument is no longer recoverable — the bisection then returns the
2496
- // smallest argument that reproduces d.
2460
+ // Inverses of a{b}c = d: d.hyper_log(a)(b) = c, d.hyper_root(c)(b) = a.
2461
+ // b = 0/1 use exact division and logarithms; b ≥ 2 bisects on the monotone
2462
+ // arrow engine. For levels b beyond maxCols the forward arrow diagonalizes
2463
+ // into one [1|b] row and the argument is not recoverable — the bisection
2464
+ // returns the smallest argument reproducing d.
2497
2465
  function hyperBisect(f, target, bound) {
2498
2466
  // smallest integer x ≥ 1 with f(x) ≥ target (f monotone nondecreasing)
2499
2467
  var lo = MetaNum.ONE.clone();
@@ -2515,13 +2483,11 @@
2515
2483
  return hi;
2516
2484
  }
2517
2485
 
2518
- // Continuous inverse used as the interpolation ANCHOR of a fractional level:
2519
- // the real c with a{b}c = d, searched by bisection on doubles (arrow()
2520
- // evaluates fractional arguments). hyperBisect only searches integers and
2521
- // therefore overshoots (θ0 = 2 where the true value is 1.0414), which makes
2522
- // the geometric interpolation θ = θ0·(y/θ0)^f run BACKWARDS (y/θ0 < 1) and
2523
- // breaks the monotonicity of x{y}y — arrow(10,1.5,1.5) came out smaller than
2524
- // arrow(10,1.1,1.1). Returns null when d cannot be bracketed.
2486
+ // Continuous inverse — the interpolation ANCHOR of a fractional level: the
2487
+ // real c with a{b}c = d, bisected on doubles. hyperBisect only searches
2488
+ // integers and overshoots (θ0 = 2 where the truth is 1.0414), which made the
2489
+ // geometric interpolation run BACKWARDS and broke the monotonicity of x{y}y
2490
+ // (arrow(10,1.5,1.5) < arrow(10,1.1,1.1)). null when d cannot be bracketed.
2525
2491
  function hyperAnchorReal(a, b, d) {
2526
2492
  try {
2527
2493
  var lo = 0, hi = 1, it = 0;
@@ -2769,19 +2735,16 @@
2769
2735
  };
2770
2736
 
2771
2737
  // ---------------------------------------------------------------------------
2772
- // Unified ordinal hyperoperation engine — implements README rules 1-4:
2738
+ // Unified ordinal hyperoperation engine — README rules 1-4:
2773
2739
  // rule 1: x{0}y = x*y
2774
2740
  // rule 2: x{α}1 = x; x{α}y = (x{α-1}) iterated (y-1) times from x
2775
2741
  // rule 3: x{λ}y = x{λ[y]}y (fundamental sequence at y)
2776
2742
  // rule 4: operations compose right-to-left
2777
- // Representation rules for operands/intermediates beyond MSI:
2778
- // x{α}y ≈ 10{α}y when y > MSI → y itself plus one ordinal row [1|α]
2779
- // (the iteration count y is unrepresentable, so it diagonalizes to a
2780
- // single α-level marker — the supremum of count-limited iterations).
2781
- // Swallowing (right-to-left composition): applying level β to a value
2782
- // whose top ordinal row level is γ:
2783
- // β > γ → push a new [k|β] row ; β = γ → top count += k ; β < γ → no change
2784
- // (e.g. 10{ω}10{ω+2}10 = 10{ω+2}10). Counts are always capped at MSI.
2743
+ // y > MSI: x{α}y ≈ 10{α}y — y plus one row [1|α] (the count diagonalizes to
2744
+ // a single α-level marker, the supremum of count-limited iterations).
2745
+ // Swallowing: applying level β on top of row level γ — β > γ pushes [k|β],
2746
+ // β = γ adds to the top count, β < γ is swallowed (10{ω}10{ω+2}10 =
2747
+ // 10{ω+2}10). Counts are capped at MSI.
2785
2748
  // ---------------------------------------------------------------------------
2786
2749
 
2787
2750
  var COEFF_BOUND = 100; // cascade bound: larger coefficients supremum-collapse
@@ -2905,17 +2868,12 @@
2905
2868
 
2906
2869
  // ---------------------------------------------------------------------------
2907
2870
  // Compact "layer marker" values for levels at or above ω^ω (README L17).
2908
- // Such a level has no finite CNF coefficient row, so the result of x{α}y is
2909
- // stored as the diagonal value of the reduced level (one rule-3 step):
2910
- // layer L >= 1, rows [count, a1, …, ap] →
2911
- // 10{ ω^ω^…((L-1) ω^'s)…^( Σ_i ω^(ord_i)·count_i + Σ_j ω^j·r_j ) }10
2912
- // with ord_i = ω^(p-1)·ap + … + ω·a2 + a1.
2913
- // Examples: 10{ω^y}10 = L1 [[0],[1,y]]; 10{ω^ω}10 = L1 [[0],[1,0,1]];
2914
- // 10{ω^ω·y}10 = L1 [[0],[y,0,1]]; 10{ω^(ω+y)}10 = L1 [[0],[1,y,1]];
2915
- // 10{ω^(ω·y)}10 = L2 [[0],[y,1]]; 10{ω^(ω^y)}10 = L3 [[y]];
2916
- // 10{ω^ω^…^ω(y ω's)}10 = L_y [[0],[1,1]].
2917
- // A marker is always stored in STANDARD FORM (Q._standardizeLayerValue):
2918
- // finite-level rows merge into r0 and the layer drops as far as it can.
2871
+ // layer L >= 1 with rows [count, a1..ap] (ord_i = ω^(p-1)·ap+…+a1) encodes
2872
+ // 10{ ω^ω^…((L-1) ω^'s)…^( Σ_i ω^(ord_i)·count_i + Σ_j ω^j·r_j ) }10
2873
+ // e.g. 10{ω^y}10 = L1 [[0],[1,y]]; 10{ω^ω}10 = L1 [[0],[1,0,1]];
2874
+ // 10{ω^ω·y}10 = L1 [[0],[y,0,1]]; 10{ω^(ω·y)}10 = L2 [[0],[y,1]];
2875
+ // 10{ω^(ω^y)}10 = L3 [[y]]; 10{ω^ω^…^ω(y ω's)}10 = L_y [[0],[1,1]].
2876
+ // Markers are stored in STANDARD FORM (Q._standardizeLayerValue).
2919
2877
  // ---------------------------------------------------------------------------
2920
2878
  Q._layerMarker = function (r0, layer, rows) {
2921
2879
  var v = new MetaNum(0);
@@ -2927,21 +2885,15 @@
2927
2885
  return Q._standardizeLayerValue(v);
2928
2886
  };
2929
2887
 
2930
- // Standard form of a layer >= 1 value (README L17). Two rewrites, both
2931
- // preserving the encoded ordinal, applied until no longer possible:
2932
- // (a) merge: an ordinal row [count, k] holds the finite level k, i.e. the
2933
- // bracket term ω^k·count — the very term r0's own k-th entry spells
2934
- // (Σ_j ω^j·r_j). So whenever k < maxCols the row folds into r0:
2935
- // cube(10,3): [[10],[1,3],[1,0,1]] → [[10,0,0,1],[1,0,1]].
2936
- // (b) de-layer: a layer-L value whose bracket is the finite ω-polynomial β
2937
- // (no row above ω survives) equals the layer-(L-1) value carrying the
2938
- // single row [1|β] (bracket ω^β, one ω^ less above it):
2939
- // layer2 [[5],[3,1]] → layer2 [[5,3]] → layer1 [[10],[1,5,3]]
2940
- // = 10{ω^(ω*3+5)}10;
2941
- // layer3 [[3]] → layer2 [[0,0,0,1]] → layer1 [[10],[1,0,0,0,1]]
2942
- // = 10{ω^ω^3}10.
2943
- // Each de-layer step strictly lowers `layer`, so the loop terminates; the
2944
- // innermost base is written as 10 (the 10{…}10 diagonal marker).
2888
+ // Standard form of a layer >= 1 value (README L17) — two ordinal-preserving
2889
+ // rewrites, applied until neither fires:
2890
+ // (a) merge: a row [count, k] with finite k < maxCols folds into r0[k]
2891
+ // (cube(10,3): [[10],[1,3],[1,0,1]] → [[10,0,0,1],[1,0,1]]).
2892
+ // (b) de-layer: a bracket that is a finite ω-polynomial β (no row above ω)
2893
+ // equals the layer-(L-1) value with the single row [1|β] (layer2
2894
+ // [[5],[3,1]] → layer1 [[10],[1,5,3]] = 10{ω^(ω*3+5)}10).
2895
+ // Each de-layer lowers `layer`, so the loop terminates; the innermost base
2896
+ // is written as 10.
2945
2897
  function mergeFiniteRowsIntoR0(arr) {
2946
2898
  var r0 = arr[0];
2947
2899
  var keep = [];
@@ -2975,6 +2927,7 @@
2975
2927
  return v;
2976
2928
  };
2977
2929
 
2930
+
2978
2931
  Q._standardizeLayerValue = function (v) {
2979
2932
  if (!v || v.layer < 1) return v.normalize();
2980
2933
  var L = v.layer;
@@ -3021,6 +2974,8 @@
3021
2974
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
3022
2975
  if (y.eq(MetaNum.ONE)) return x.clone();
3023
2976
  if (cf.length === 0) return x.mul(y); // rule 1: x{0}y = x*y
2977
+ // B2-a: base-2 infinite-level collapse (see _hyperopFromOrdinal).
2978
+ if (x.eq(2) && y.isint() && y.gte(2) && coeffsHaveOmegaPart(cf)) return new MetaNum(4);
3024
2979
 
3025
2980
  if (!coeffsHaveOmegaPart(cf)) {
3026
2981
  // finite level: arrow() handles both small and huge operands
@@ -3073,14 +3028,10 @@
3073
3028
  return V;
3074
3029
  };
3075
3030
 
3076
- // Helper: generic hyperoperation from ordinal level (Cantor normal form coefficients).
3077
- // coeffs: [c0, c1, c2, ..., ck] where ordinal = ω^k*ck + ... + ω^2*c2 + ω*c1 + c0
3078
- // Two computation paths:
3079
- // - small operands (x ∈ [3, MSI] finite, y ∈ [3, MSI] finite, enumeration of
3080
- // ordinals below α with coefficients < y fits into maxRows): legacy
3081
- // enumeration representation (one row per ordinal below α, count = y-2)
3082
- // - everything else (any operand beyond MSI, x = 2, or enumeration too large):
3083
- // unified ordinal engine (README rules 1-4)
3031
+ // Helper: generic hyperoperation from ordinal level. coeffs are the CNF
3032
+ // coefficients [c0..ck] (ordinal = ω^k*ck+…+ω*c1+c0). Two paths: small
3033
+ // finite operands in [3, MSI] use the legacy enumeration (one row per ordinal
3034
+ // below α, count = y-2); everything else the unified engine (rules 1-4).
3084
3035
  Q._hyperopFromOrdinalRaw = function (x, y, coeffs, skipFrac) {
3085
3036
  x = new MetaNum(x);
3086
3037
  y = new MetaNum(y);
@@ -3092,12 +3043,14 @@
3092
3043
 
3093
3044
  var cf0 = trimCoeffs((coeffs || []).slice());
3094
3045
  if (cf0.length === 0) return x.mul(y); // rule 1: x{0}y = x*y
3046
+ // B2-a: for base 2 every infinite level collapses (rule 3 turns the
3047
+ // argument into 2; 2{...}2 = 2{2}2 = 4). Finite levels are excluded.
3048
+ if (x.eq(2) && y.isint() && y.gte(2) && coeffsHaveOmegaPart(cf0)) return new MetaNum(4);
3095
3049
  // Fractional level coefficients come from a fundamental sequence taken at a
3096
- // non-integer index. On the diagonal ω = x, so ω^(k)·(c+f) = ω^(k)·c +
3097
- // ω^(k-1)·(x·f) — resolve top-down until only the constant term can still be
3098
- // fractional, then turn that leftover into a fractional argument one level
3099
- // higher: x{γ+f}x = x{γ+1}(2·(x/2)^f) (README: 10{ω*2}2.1 = 10{ω+2.1}10 =
3100
- // 10{ω+3}2·5^0.1; continuous at f=0 since x{γ+1}2 = x{γ}x).
3050
+ // non-integer index. On the diagonal ω = x, so ω^k·(c+f) = ω^k·c +
3051
+ // ω^(k-1)·(x·f) — resolve top-down until only the constant term can still
3052
+ // be fractional, then raise it to a fractional argument one level up:
3053
+ // x{γ+f}x = x{γ+1}(2·(x/2)^f) (10{ω*2}2.1 = 10{ω+3}2·5^0.1).
3101
3054
  if (coeffsHaveFraction(cf0)) {
3102
3055
  var xnf = x.toNumber();
3103
3056
  if (isFinite(xnf) && xnf >= 2) {
@@ -3139,13 +3092,12 @@
3139
3092
  var bigLevel = (pred[1] || 0) >= 2;
3140
3093
  for (var bi = 2; bi < pred.length; bi++) if ((pred[bi] || 0) > 0) bigLevel = true;
3141
3094
  if (xOkS && bigLevel && ym <= 100000) {
3142
- // successor rule written in the EXPANDED form (the same generator the
3143
- // integer arguments use): the α-1 row carries the m applications as an
3095
+ // Successor rule in the EXPANDED form (the generator the integer
3096
+ // arguments use): the α-1 row carries the m applications as the
3144
3097
  // integer count ceil(y)-2 = m-1, and the fraction lives in the cascade
3145
- // depth — the first fundamental sequence is taken at the fractional
3146
- // start value x^f (x{α}(m+f) = x{α-1}^m(x^f) — exactly what the finite
3147
- // levels do: 10{3}2.1 starts from 10^0.1). Whatever fraction is left
3148
- // over lands in the base, i.e. in array[0][0].
3098
+ // depth — the first FS starts at the fractional value x^f
3099
+ // (x{α}(m+f) = x{α-1}^m(x^f), as 10{3}2.1 starts from 10^0.1). Any
3100
+ // leftover fraction lands in array[0][0].
3149
3101
  return Q._expandedHyperop(x, new MetaNum(ym + 1), cf0,
3150
3102
  Math.pow(xnfS, Number((yFracNum - ym).toPrecision(15))));
3151
3103
  }
@@ -3164,14 +3116,11 @@
3164
3116
  return Q._ordinalHyperop(x, y, cf0);
3165
3117
  }
3166
3118
  if (ym >= 1) {
3167
- // limit level: rule 3 with the FULL (fractional) index — x{λ}y =
3168
- // x{λ[y]}x. λ[y] can carry fractional coefficients (10{ω*2}2.1 =
3169
- // 10{ω+2.1}10), which the fractional-level rule above resolves, so the
3170
- // fraction of y is never thrown away (flooring it would make
3171
- // h20(10,2.1) = h20(10,2)).
3172
- // Nested (skipFrac: the successor rule is already iterating a fractional
3173
- // start value) the index is floored — otherwise every application would
3174
- // take another fractional fundamental sequence and recurse forever.
3119
+ // Limit level: rule 3 with the FULL (fractional) index — λ[y] can
3120
+ // carry fractional coefficients (10{ω*2}2.1 = 10{ω+2.1}10), resolved by
3121
+ // the fractional-level rule above, so the fraction is never dropped.
3122
+ // Nested (skipFrac) the index is floored, else every application would
3123
+ // take another fractional FS and recurse forever.
3175
3124
  var fsIdx = skipFrac ? Math.floor(yFracNum) : yFracNum;
3176
3125
  return Q._hyperopFromOrdinalRaw(x, x, fsCoeffs(cf0, fsIdx), skipFrac);
3177
3126
  }
@@ -3208,29 +3157,16 @@
3208
3157
 
3209
3158
  // ---------------------------------------------------------------------------
3210
3159
  // Expanded (cascade) form of x{α}y for FINITE operands in [3, MSI] — README
3211
- // rules 1-4 written out row by row. The rows are generated TOP-DOWN so a
3212
- // huge fundamental sequence (y up to MSI) costs nothing: generation stops as
3213
- // soon as the array budget is filled, keeping the LARGEST rows.
3214
- //
3215
- // successor α = β + m (m = c0 > 0): x{α}y = x{β+m-1}^(y-2)(x{β+m-1}x),
3216
- // so the row at β+m-1 carries y-2 applications and every row below it
3217
- // (β+m-2 … β, then the cascade of β) comes from decomposing with the
3218
- // BASE x as operand and therefore carries x-2 (h13(10,20) → [8,0,1],
3219
- // [8,1,1], [18,2,1] — only the top row follows y).
3220
- // limit α (c0 = 0): rule 3 gives x{α}opd = x{α[opd]}x, so the operand turns
3221
- // into the base x and every row carries x-2 — including for 100 < y ≤ MSI
3222
- // (h20(10,1000) stays an expanded cascade, not a one-row marker).
3160
+ // rules 1-4 row by row. Rows are generated TOP-DOWN (a huge fundamental
3161
+ // sequence costs nothing; the budget keeps the LARGEST rows):
3162
+ // successor α = β+m: x{α}y = x{β+m-1}^(y-2)(x{β+m-1}x) — only the top row
3163
+ // follows y, every row below carries x-2 (h13(10,20) → [8,0,1],[8,1,1],[18,2,1]).
3164
+ // limit α: rule 3 turns the operand into the base x, so every row carries x-2.
3165
+ // Only array[0][0] may be non-integer (same contract as arrow()); a fractional
3166
+ // argument enters as the outer count ceil(y)-2, the fractional start value x^f
3167
+ // of the first fundamental sequence (`fsOpd`), or a leftover constant term
3168
+ // carried into the base's finite level index (`.baseIdx`).
3223
3169
  // ---------------------------------------------------------------------------
3224
- // Only array[0][0] (the base's value slot) may ever be non-integer — the same
3225
- // contract as arrow(): every row count and every row coefficient is an integer.
3226
- // A fractional argument therefore enters in two integer-safe places:
3227
- // - the outer count is `yn - 2` with yn = ceil(y) (an integer);
3228
- // - the rest of the fraction sits in the CASCADE DEPTH: the first
3229
- // fundamental sequence is taken at the fractional start value x^f
3230
- // (x{α}(m+f) = x{α-1}^m(x^f)), and any fractional constant term left over
3231
- // is carried into the base's finite level index (x{10.16}x), so it ends up
3232
- // as the fractional array[0][0] exactly like arrow() does.
3233
- // `fsOpd` is that fractional start value; `.baseIdx` returns the base index.
3234
3170
  Q._cascadeRows = function (xn, cf, yn, budget, fsOpd) {
3235
3171
  var rows = [];
3236
3172
  if (!(budget >= 1)) return rows;
@@ -3805,25 +3741,27 @@
3805
3741
  // ---------------------------------------------------------------------------
3806
3742
 
3807
3743
  // ---------------------------------------------------------------------------
3808
- // Hyperoperations from ω^ω up to ε₀ — README rules 1-4 with the unified
3809
- // limit rule n{λ}b = n{λ[b]}n (the final operand is the BASE n, never b).
3810
- // Levels ≥ ω^ω have no finite CNF coefficient row, so — except where the
3811
- // reduced level λ[y] still fits a layer-0 ordinal row — the result is stored
3812
- // as the compact layer marker of λ[y] (see Q._layerMarker).
3744
+ // Hyperoperations from ω^ω up to ε₀ — README rules 1-4 with the unified limit
3745
+ // rule n{λ}b = n{λ[b]}n (the final operand is the BASE n). Levels ≥ ω^ω have
3746
+ // no finite CNF row, so — unless λ[y] still fits a layer-0 row — the result
3747
+ // is the compact layer marker of λ[y] (Q._layerMarker).
3813
3748
  // ---------------------------------------------------------------------------
3814
3749
 
3815
- // iter (ω^ω): (ω^ω)[y] = ω^y → x{ω^ω}y = x{ω^y}x
3816
- // e.g. iter(3,5) = 3{ω^5}3 = 3{ω^4*3}3 = … = 3{ω^4*2+ω^3*2+ω^2*2+ω*2+2}3…
3817
- // (whole fundamental-sequence cascade → layer 0 multi-row array)
3818
- // for y >= maxCols the ω^y row no longer fits → layer=1 marker [[r0],[1,y]]
3819
- // (= 10{ω^y}10), and for y > MSI the operand is unrepresentable → the
3820
- // ω^ω marker row [1,0,1] (= 10{ω^ω}10).
3750
+ // iter (ω^ω): (ω^ω)[y] = ω^y → x{ω^ω}y = x{ω^y}x — the whole
3751
+ // fundamental-sequence cascade as a layer-0 multi-row array. For y >=
3752
+ // maxCols the ω^y row no longer fits → layer-1 marker [[r0],[1,y]]
3753
+ // (= 10{ω^y}10); for y > MSI → the ω^ω marker row [1,0,1].
3821
3754
  P.iterate = P.iter = P.hww = function (y) {
3822
3755
  var x = this.clone();
3823
3756
  y = new MetaNum(y);
3824
3757
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
3825
3758
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
3826
3759
  if (y.eq(MetaNum.ONE)) return x.clone();
3760
+ // rule 3 collapses x{λ}y to x{λ[y]}x; for x=2 the argument becomes 2 and
3761
+ // every further FS/successor step keeps it there, so the cascade ends at
3762
+ // 2{...}2 = 2{2}2 = 4 for ANY limit/successor level λ and integer y >= 2
3763
+ // (issue #17 D07/B2-a). Finite levels are excluded (2{1}3 = 8).
3764
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
3827
3765
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
3828
3766
 
3829
3767
  // iterate(x,y) = x{ω^ω}y. Rule 3 with the fundamental sequence
@@ -3934,18 +3872,17 @@
3934
3872
  };
3935
3873
 
3936
3874
  // itermult (ω^ω+1): successor level — x{ω^ω+1}y = x{ω^ω} applied y-1 times
3937
- // to x (rule 2), i.e. itmu(3,k) = 3{ω^ω}3{ω^ω}…3 with k 3's.
3938
- // k = 2 → x{ω^ω}x = iterate(x,x) exactly; 1 < k < 2 → x{ω^ω}(x^(k-1)).
3939
- // k > 2 → layer=1 marker [[k-1],[1,0,1]] = 10{ω^ω+(k-1)}10: any finite
3940
- // number of ω^ω applications stays strictly below ω^ω·2, so the count
3941
- // lives in the constant term (ω^ω + n) — monotone in k and still below
3942
- // cuboiter's ω^ω+ω^k.
3875
+ // to x (rule 2). k = 2 → iterate(x,x) exactly; 1 < k < 2 → x{ω^ω}(x^(k-1)).
3876
+ // k > 2 → layer-1 marker [[k-1],[1,0,1]] = 10{ω^ω+(k-1)}10: finitely many
3877
+ // ω^ω applications stay below ω^ω·2, so the count lives in the constant term
3878
+ // (monotone in k, still below cuboiter's ω^ω+ω^k).
3943
3879
  P.itermult = P.itmu = P.hw01 = function (y) {
3944
3880
  var x = this.clone();
3945
3881
  y = new MetaNum(y);
3946
3882
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
3947
3883
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
3948
3884
  if (y.eq(MetaNum.ONE)) return x.clone();
3885
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
3949
3886
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
3950
3887
  var yc = metaFiniteCount(y);
3951
3888
  if (yc <= MAX_SAFE_INTEGER) {
@@ -4011,6 +3948,7 @@
4011
3948
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
4012
3949
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
4013
3950
  if (y.eq(MetaNum.ONE)) return x.clone();
3951
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
4014
3952
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
4015
3953
  var yc = metaFiniteCount(y);
4016
3954
  if (yc <= MAX_SAFE_INTEGER) {
@@ -4072,6 +4010,7 @@
4072
4010
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
4073
4011
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
4074
4012
  if (y.eq(MetaNum.ONE)) return x.clone();
4013
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
4075
4014
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
4076
4015
  var yc = metaFiniteCount(y);
4077
4016
  if (yc <= MAX_SAFE_INTEGER) {
@@ -4126,6 +4065,7 @@
4126
4065
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
4127
4066
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
4128
4067
  if (y.eq(MetaNum.ONE)) return x.clone();
4068
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
4129
4069
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
4130
4070
  var yc = metaFiniteCount(y);
4131
4071
  if (yc <= MAX_SAFE_INTEGER) {
@@ -4180,6 +4120,7 @@
4180
4120
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
4181
4121
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
4182
4122
  if (y.eq(MetaNum.ONE)) return x.clone();
4123
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
4183
4124
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
4184
4125
  var yc = metaFiniteCount(y);
4185
4126
  if (yc <= MAX_SAFE_INTEGER) {
@@ -4241,6 +4182,7 @@
4241
4182
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
4242
4183
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
4243
4184
  if (y.eq(MetaNum.ONE)) return x.clone();
4185
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
4244
4186
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
4245
4187
  var yc = metaFiniteCount(y);
4246
4188
  if (yc <= MAX_SAFE_INTEGER) {
@@ -4314,6 +4256,7 @@
4314
4256
  if (x.isNaN() || y.isNaN()) return MetaNum.NaN.clone();
4315
4257
  if (x.eq(MetaNum.ONE)) return MetaNum.ONE.clone();
4316
4258
  if (y.eq(MetaNum.ONE)) return x.clone();
4259
+ if (x.eq(2) && y.isint() && y.gte(2)) return new MetaNum(4);
4317
4260
  if (y.lte(MetaNum.ZERO)) return MetaNum.NaN.clone();
4318
4261
  // ε₀[2] = ω^ω, so epsilonate(x,2) = x{ω^ω}x = iterate(x,x) exactly (the
4319
4262
  // same value itermult(x,2) produces — x{ε₀}2 = x{ω^ω+1}2).
@@ -4678,9 +4621,22 @@
4678
4621
  }
4679
4622
  // Always include layer symbol for layers 1-10
4680
4623
  if (this.layer >= 1 && finOps === "" && baseStr !== "") {
4681
- return sym + ordTokens.join("") + baseStr;
4624
+ // "^count" tokens are space-separated (see the layer-0 path)
4625
+ var hasPowS = false;
4626
+ for (var ps = 0; ps < ordTokens.length; ps++) {
4627
+ if (ordTokens[ps].indexOf("^") !== -1) { hasPowS = true; break; }
4628
+ }
4629
+ return sym + ordTokens.join(hasPowS ? " " : "") + (hasPowS ? " " : "") + baseStr;
4630
+ }
4631
+ // "^count" tokens are space-separated so the parser can split the
4632
+ // count from the trailing base digits (see the layer-0 path).
4633
+ var hasPowL = false;
4634
+ for (var pl = 0; pl < ordTokens.length; pl++) {
4635
+ if (ordTokens[pl].indexOf("^") !== -1) { hasPowL = true; break; }
4682
4636
  }
4683
- return sym + ordTokens.join("") + (finOps ? finOps : "") + baseStr;
4637
+ var bodyL = ordTokens.join(hasPowL ? " " : "");
4638
+ if (hasPowL && (finOps || baseStr)) bodyL += " ";
4639
+ return sym + bodyL + (finOps ? finOps : "") + baseStr;
4684
4640
  }
4685
4641
  }
4686
4642
 
@@ -4838,7 +4794,16 @@
4838
4794
  var hasAa = finOps && finOps.indexOf("Aa") !== -1;
4839
4795
  var prefix = useExclaim ? "!" : "";
4840
4796
  var baseNum = (useExclaim || hasAa) ? "" : decimalPlaces(this.array[0][0], 6);
4841
- return prefix + ordTokens.join("") + (finOps ? finOps : "") + baseNum;
4797
+ // Tokens carrying an explicit "^count" are space-separated (same rule
4798
+ // as formatFiniteOps) so the parser can tell the count from the
4799
+ // trailing base digits: "Ijj^8 Iji^8 … Iib^8 10", not "Iib^810".
4800
+ var hasPow = false;
4801
+ for (var pi = 0; pi < ordTokens.length; pi++) {
4802
+ if (ordTokens[pi].indexOf("^") !== -1) { hasPow = true; break; }
4803
+ }
4804
+ var body = ordTokens.join(hasPow ? " " : "");
4805
+ if (hasPow && (finOps || baseNum)) body += " ";
4806
+ return prefix + body + (finOps ? finOps : "") + baseNum;
4842
4807
  }
4843
4808
  }
4844
4809
 
@@ -5132,6 +5097,10 @@
5132
5097
  x.layer = 0;
5133
5098
 
5134
5099
  var s = input.trim();
5100
+ // Displays group digits with commas ("29,657", "1,000,000") — strip them
5101
+ // so every format() output parses back (digit-comma-digit only, so BEAF
5102
+ // strings like "{10, 16}" and JSON payloads are untouched).
5103
+ s = s.replace(/(\d),(?=\d)/g, "$1");
5135
5104
  if (s === "" || s === "0") {
5136
5105
  return x;
5137
5106
  }
@@ -5553,11 +5522,10 @@
5553
5522
 
5554
5523
  // Parse spaced letter-chain notation (round-trip of toString output):
5555
5524
  // "M^7 L^8 K^8 ... E^8 10000000000" finite levels with ^counts
5556
- // "GF^2 E^3 123" letters + ^counts (last letter gets count)
5525
+ // "GF^2 E^3 123" letters + ^counts (last gets count)
5557
5526
  // "3Aa25 100" high finite level (> 22) with base
5558
- // "AaAa E^8 100" compact ordinal tokens + spaced chain
5559
- // "F^9 EE100" spaced chain + compact letters + base
5560
- // Must come before aaMatch so "3Aa25 100" keeps its trailing base value.
5527
+ // "AaAa E^8 100" / "F^9 EE100" compact tokens + spaced chain
5528
+ // Must come before aaMatch so "3Aa25 100" keeps its trailing base.
5561
5529
  var chainMatch = rem.match(/^((?:[A-Z][a-z]+)*)((?:(?:[A-Z]+\^\d+|\d+Aa\d+)\s+)+)([A-Z]*)(\d+(?:\.\d+)?)\s*$/);
5562
5530
  if (chainMatch) {
5563
5531
  var chainOk = true;
@@ -5660,19 +5628,34 @@
5660
5628
  }
5661
5629
  }
5662
5630
 
5663
- var aaMatch = rem.match(/^(\d+)Aa(\d+)/i);
5631
+ // #19 — the Aa diagonal (README: Aaα = 10{α}10, so the bare Aaα and the
5632
+ // binary 2Aaα coincide; the general binary form is αAaβ = 10{β+1}α).
5633
+ // The old path stored the raw coefficient row [10,0,…,0,count] — that is
5634
+ // 10{β+1}(count+1), one application too many: 2Aa3 came out as
5635
+ // [[10^10,8,8,1]] (= 10{4}3) instead of 10{3}10 = [[10^10,8,8]].
5636
+ var aaMatch = rem.match(/^(\d+)Aa(\d+(?:\.\d+)?)$/i);
5664
5637
  if (aaMatch) {
5665
- var aaCount = aaMatch[1] ? Number(aaMatch[1]) : 1;
5638
+ var aaCount = Number(aaMatch[1]);
5666
5639
  var aaN = Number(aaMatch[2]);
5667
- if (!isNaN(aaN) && isFinite(aaN) && aaN >= 1 && aaN === Math.floor(aaN)) {
5668
- if (aaN < MetaNum.maxCols) {
5669
- x.array[0] = [10];
5670
- x.array[0][aaN] = aaCount;
5671
- } else {
5672
- x.array = [[10], [aaCount, aaN]];
5673
- }
5674
- if (negateIt) x.sign = -1;
5675
- return x.normalize();
5640
+ if (!isNaN(aaN) && isFinite(aaN) && aaN >= 0 && isFinite(aaCount) && aaCount >= 1) {
5641
+ var aaVal = MetaNum.TEN.clone().arrow(aaN + 1)(aaCount); // 10{β+1}α
5642
+ if (negateIt) aaVal.sign = -1;
5643
+ return aaVal;
5644
+ }
5645
+ }
5646
+
5647
+ // Bare Aa<n> (no mantissa): the diagonal itself — Aaα = 10{α}10 for
5648
+ // every real α (README "Defining Aa"). A level below 1 has no engine
5649
+ // arrow, so apply rule (iii): 10{α}10 = 10{1}(2·5^α).
5650
+ var aaBareMatch = rem.match(/^Aa(\d+(?:\.\d+)?)$/i);
5651
+ if (aaBareMatch) {
5652
+ var abN = Number(aaBareMatch[1]);
5653
+ if (isFinite(abN) && abN >= 0) {
5654
+ var abVal;
5655
+ if (abN < 1) abVal = MetaNum.TEN.clone().arrow(1)(2 * Math.pow(5, abN));
5656
+ else abVal = MetaNum.TEN.clone().arrow(abN)(MetaNum.TEN.clone());
5657
+ if (negateIt) abVal.sign = -1;
5658
+ return abVal;
5676
5659
  }
5677
5660
  }
5678
5661
 
@@ -5688,13 +5671,70 @@
5688
5671
  return innerS.normalize();
5689
5672
  }
5690
5673
 
5691
- // Canonical diagonal-letter output "mantissa LETTER β" where LETTER is
5692
- // any multi-letter token ending in 'a' (Aa, Ba, Aaa, Aaaa, …), with the
5693
- // dlsdl diagonal mantissa α ∈ [2,10):
5694
- // exact anchor α=2.000 -> the plain letter application LETTER(β)
5695
- // (2·5^0=2 adds nothing);
5696
- // fractional α -> compact smooth row [α, β] (r0=[1]), the same
5697
- // representation the engine emits for 10{β}(structured counts).
5674
+ // !Aaα with a real (non-integer) α — decision 1B: !Aaα ≡ A(a×⌊α⌋)(α),
5675
+ // the letter token with ⌊α⌋ lowercase a's applied at argument α. Keeps
5676
+ // the integer anchors and extends them continuously inside each unit
5677
+ // interval (!Aa1.5 = Aa1.5, !Aa2.5 = Aaa2.5). Must run before
5678
+ // diagBinMatch: "!Aa1.5" has no mantissa in front.
5679
+ var bangAaMatch = rem.match(/^!Aa(\d+\.\d+)$/);
5680
+ if (bangAaMatch) {
5681
+ var baA = Number(bangAaMatch[1]);
5682
+ if (isFinite(baA) && baA > 0) {
5683
+ var baN = Math.max(1, Math.floor(baA));
5684
+ var baTok = "A" + new Array(baN + 1).join("a");
5685
+ var baVal = Q.fromString(baTok + String(baA));
5686
+ if (negateIt) baVal.sign = -1;
5687
+ return baVal;
5688
+ }
5689
+ }
5690
+
5691
+ // !αAaβ binary diagonal (notation-semantics §2, decision 1B):
5692
+ // !αAaβ = !Aa(β + log₅(α/2))
5693
+ // Built as the de-layered instance A(a×⌊x⌋)(x) when the row fits maxCols,
5694
+ // else the layer-1 marker. Must run before diagBinMatch so the α≠2 case
5695
+ // stops using the lossy compact row. α = 1.000 (legacy "no mantissa") is
5696
+ // left to the 1.0+-strip below; α = 1 without decimals follows the
5697
+ // formula.
5698
+ var aaBinMatch = rem.match(/^!(\d+(?:\.\d+)?)Aa(\d+(?:\.\d+)?(?:[Ee]\d+)?)$/);
5699
+ if (aaBinMatch) {
5700
+ var aaMant = Number(aaBinMatch[1]);
5701
+ var aaBeta = Number(aaBinMatch[2]);
5702
+ var aaSkipLegacy = (aaMant === 1 && aaBinMatch[1].indexOf('.') >= 0);
5703
+ if (!aaSkipLegacy && isFinite(aaMant) && aaMant > 0 &&
5704
+ isFinite(aaBeta) && aaBeta >= 0) {
5705
+ var aaX = aaBeta + Math.log(aaMant / 2) / Math.log(5);
5706
+ if (aaX >= 1 && aaX === Math.floor(aaX)) {
5707
+ // #19: an INTEGER !Aa<n> is the full rule-3 cascade of 10{ω^n}10
5708
+ // (layer 0) — "!" adds one ω^ to the level. Past the row budget
5709
+ // bangAaInteger goes one layer up with the de-!-ed compact.
5710
+ var anVal = bangAaInteger(aaX, 0);
5711
+ anVal.sign = 1;
5712
+ if (negateIt) anVal.sign = -1;
5713
+ return anVal;
5714
+ }
5715
+ var aaK = Math.max(1, Math.floor(aaX));
5716
+ var aaVal = new MetaNum();
5717
+ if (aaX >= 1 && aaK + 2 <= MetaNum.maxCols) {
5718
+ var aaRow = [1];
5719
+ for (var ai = 0; ai < aaK; ai++) aaRow.push(0);
5720
+ aaRow.push(1);
5721
+ aaVal.array = [[aaX], aaRow];
5722
+ aaVal.layer = 0;
5723
+ } else {
5724
+ aaVal.array = [[aaX], [1, 0, 1]];
5725
+ aaVal.layer = (aaX >= 1) ? 1 : 0;
5726
+ }
5727
+ aaVal.sign = 1;
5728
+ aaVal.normalize();
5729
+ if (negateIt) aaVal.sign = -1;
5730
+ return aaVal;
5731
+ }
5732
+ }
5733
+
5734
+ // Canonical diagonal-letter output "mantissa LETTER β" (LETTER any
5735
+ // multi-letter token ending in 'a'), with the dlsdl diagonal mantissa
5736
+ // α ∈ [2,10): the exact anchor α=2.000 gives the plain letter application
5737
+ // LETTER(β); a fractional α gives the compact smooth row [α, β] (r0=[1]).
5698
5738
  var diagBinMatch = rem.match(/^([!@#\$%&~<>?]?)(\d+\.\d+)([A-Z][a-z]+)(\d[\d,]*)\s*$/);
5699
5739
  if (diagBinMatch) {
5700
5740
  var dbSym = diagBinMatch[1];
@@ -5726,8 +5766,27 @@
5726
5766
  // the fractional-argument machinery and is not accepted here.
5727
5767
  rem = rem.replace(/^([!@#\$%&~<>?]?)1\.0+(?=[A-Z])/, '$1');
5728
5768
 
5769
+ // #19 — the symbol layers of the Aa diagonal: every symbol adds one ω^
5770
+ // (!Aa<n> = 10{ω^n}10 layer 0, @Aa<n> layer 1, #Aa<n> layer 2, …), so the
5771
+ // same rule-3 cascade is stored and `layer` carries the extra ω^'s.
5772
+ // Mantissa 2 (or 2.000) is the diagonal anchor (2·5^0 = 2); other
5773
+ // mantissas keep the smooth decision-1B path below.
5774
+ var aaSymMatch = rem.match(/^([!@#\$%&~<>?])(2(?:\.0+)?)?Aa(\d+)$/);
5775
+ if (aaSymMatch) {
5776
+ var asIdx = "!@#$%&~<>?".indexOf(aaSymMatch[1]);
5777
+ var asN = Number(aaSymMatch[3]);
5778
+ if (asIdx >= 0 && isFinite(asN) && asN >= 1 && asN === Math.floor(asN)) {
5779
+ var asVal = bangAaInteger(asN, asIdx); // "!" → layer 0, "@" → 1, …
5780
+ asVal.sign = 1;
5781
+ if (negateIt) asVal.sign = -1;
5782
+ return asVal;
5783
+ }
5784
+ }
5785
+
5729
5786
  // Handle layer symbol prefix + letter pattern + optional finOps + number (e.g., !Abcd1234, !AaE16, @Bcde500)
5730
- var symPrefixMatch = rem.match(/^([!@#\$%&~<>?])([A-Z][a-z]+(?:[A-Z][a-z]+)*)([A-Z]*)(\d+)\s*$/);
5787
+ // Tokens may carry "^count" application counts and be space-separated —
5788
+ // the toString spelling of multi-row ordinal cascades ("!Ijj^8 … 10").
5789
+ var symPrefixMatch = rem.match(/^([!@#\$%&~<>?])((?:[A-Z][a-z]+(?:\^\d+)?\s*)+)([A-Z]*)((?:\d+(?:\.\d+)?(?:[Ee]\d+)?))\s*$/);
5731
5790
  if (symPrefixMatch) {
5732
5791
  var SYMBOL_LAYERS_P = {'!': 1, '@': 2, '#': 3, '$': 4, '%': 5, '&': 6, '~': 7, '<': 8, '>': 9, '?': 10};
5733
5792
  x.layer = SYMBOL_LAYERS_P[symPrefixMatch[1]] || 1;
@@ -5735,30 +5794,32 @@
5735
5794
  rem = symPrefixMatch[2] + (symPrefixMatch[3] || '') + symPrefixMatch[4];
5736
5795
  }
5737
5796
 
5738
- // Ordinal-prefix chain with a full number argument — the argument may be
5739
- // a plain integer ("AaG5"), a decimal ("AaG5.5"), or a sci-notation value
5740
- // ("AaGF7.626E12", the round-trip of format() displays like "AaGF7.626E12"
5741
- // whose letter chain carries a huge finite-arg). The old (\d+) regex ate
5742
- // only "7" and silently dropped ".626E12".
5743
- var oaMatch = rem.match(/^((?:[A-Z][a-z]+)+)([A-Z]*)((?:\d+(?:\.\d+)?(?:[Ee]\d+)?))$/);
5797
+ // Ordinal-prefix chain with a full number argument — plain integer
5798
+ // ("AaG5"), decimal ("AaG5.5") or sci-notation ("AaGF7.626E12"); the old
5799
+ // (\d+) regex ate only "7" and dropped ".626E12". Each token may carry
5800
+ // an explicit count ("Ijj^8", the toString spelling of a row whose count
5801
+ // reached the ^n form) and tokens may be space-separated (keeping "^8"
5802
+ // apart from the trailing base digits).
5803
+ var oaMatch = rem.match(/^((?:[A-Z][a-z]+(?:\^\d+)?\s*)+)([A-Z]*)((?:\d+(?:\.\d+)?(?:[Ee]\d+)?))$/);
5744
5804
  if (oaMatch) {
5745
5805
  var oaFullPrefix = oaMatch[1];
5746
5806
  var oaFinOps = oaMatch[2];
5747
5807
  var oaN = Number(oaMatch[3]);
5748
5808
  if (!isNaN(oaN) && isFinite(oaN) && oaN >= 0) {
5749
5809
  var oaTokens = [];
5750
- var oaTokenRegex = /[A-Z][a-z]+/g;
5810
+ var oaTokenRegex = /[A-Z][a-z]+(?:\^(\d+))?/g;
5751
5811
  var oaTm;
5752
5812
  while ((oaTm = oaTokenRegex.exec(oaFullPrefix)) !== null) {
5753
- oaTokens.push(oaTm[0]);
5813
+ oaTokens.push({ token: oaTm[0].split("^")[0], rep: oaTm[1] ? Number(oaTm[1]) : 1 });
5754
5814
  }
5755
5815
 
5756
5816
  var oaGroups = [];
5757
5817
  for (var ti = 0; ti < oaTokens.length; ti++) {
5758
- if (oaGroups.length > 0 && oaGroups[oaGroups.length - 1].token === oaTokens[ti]) {
5759
- oaGroups[oaGroups.length - 1].count++;
5818
+ var ot = oaTokens[ti];
5819
+ if (oaGroups.length > 0 && oaGroups[oaGroups.length - 1].token === ot.token) {
5820
+ oaGroups[oaGroups.length - 1].count += ot.rep;
5760
5821
  } else {
5761
- oaGroups.push({token: oaTokens[ti], count: 1});
5822
+ oaGroups.push({token: ot.token, count: ot.rep});
5762
5823
  }
5763
5824
  }
5764
5825
 
@@ -5889,6 +5950,39 @@
5889
5950
  if (negateIt) x.sign = -1;
5890
5951
  return x.normalize();
5891
5952
  }
5953
+ // The remainder may be a sci-notation number beyond the double range
5954
+ // ("1.537E924") — Number() overflows to Infinity and the letter counts
5955
+ // above were skipped, so the display "EE1.537E924" (the format of
5956
+ // [[924.19,3]]) used to lose BOTH E's on parse. Convert to the log
5957
+ // form and apply the counts on top: E^k(10^L) = [L, k+1].
5958
+ var sciRest = rem.match(/^([\d.]+)[Ee](-?\d+)\s*$/);
5959
+ if (sciRest) {
5960
+ var sciMantR = Number(sciRest[1]);
5961
+ var sciExpR = Number(sciRest[2]);
5962
+ if (!isNaN(sciMantR) && isFinite(sciMantR) && isFinite(sciExpR) && sciMantR > 0) {
5963
+ var logValR = Math.log10(sciMantR) + sciExpR;
5964
+ var countsR = {};
5965
+ var maxIdxR = 0;
5966
+ for (var ri = 0; ri < prefix.length; ri++) {
5967
+ var letterPosR = prefix.charCodeAt(ri) - 64;
5968
+ if (letterPosR >= 5) {
5969
+ var idxR = letterPosR - 4;
5970
+ countsR[idxR] = (countsR[idxR] || 0) + 1;
5971
+ maxIdxR = Math.max(maxIdxR, idxR);
5972
+ }
5973
+ }
5974
+ if (maxIdxR === 1) {
5975
+ x.array[0] = [logValR, (countsR[1] || 0) + 1];
5976
+ } else {
5977
+ x.array[0] = [logValR, 1];
5978
+ for (var idx3 = 1; idx3 <= maxIdxR; idx3++) {
5979
+ x.array[0][idx3] = (x.array[0][idx3] || 0) + (countsR[idx3] || 0);
5980
+ }
5981
+ }
5982
+ if (negateIt) x.sign = -1;
5983
+ return x.normalize();
5984
+ }
5985
+ }
5892
5986
  }
5893
5987
 
5894
5988
  // Parse scientific notation with extreme exponents (e.g., 1E-1000000, 1E1000000)
@@ -5928,15 +6022,11 @@
5928
6022
 
5929
6023
 
5930
6024
  // ==================== BEAF Ordinal Helpers ====================
5931
- // Build ordinal coefficient array from BEAF args:
5932
- // BEAF(a,b,c,d,e,f,...) = a{...+ω^3*(f-1)+ω^2*(e-1)+ω*(d-1)+c}b
5933
- // coeffs[0] = c (ω^0 = constant term, no decrement)
5934
- // coeffs[1] = d-1 (ω^1 coefficient)
5935
- // coeffs[2] = e-1 (ω^2 coefficient)
5936
- // coeffs[3] = f-1 (ω^3 coefficient)
5937
- // An argument whose value exceeds MSI (or carries ordinal structure) cannot
5938
- // serve as an exact coefficient: it is reported in hugeArgs and the caller
5939
- // supremum-collapses it (ω^i*HUGE ≈ ω^(i+1)).
6025
+ // BEAF(a,b,c,d,e,f,...) = a{...+ω^3*(f-1)+ω^2*(e-1)+ω*(d-1)+c}b, so
6026
+ // coeffs = [c, d-1, e-1, f-1, …] (the constant term is not decremented).
6027
+ // An argument beyond MSI (or with ordinal structure) cannot be an exact
6028
+ // coefficient: it is reported in hugeArgs and supremum-collapsed
6029
+ // (ω^i*HUGE ≈ ω^(i+1)).
5940
6030
  Q._buildOrdinalCoeffs = function(args) {
5941
6031
  var coeffs = [];
5942
6032
  var hugeArgs = [];
@@ -5957,13 +6047,11 @@
5957
6047
  return { coeffs: coeffs, hugeArgs: hugeArgs };
5958
6048
  };
5959
6049
 
5960
- // Ordinal BEAF computation for 4+ arguments:
5961
- // BEAF(a,b,c,d,...) = a{...+ω*d+c}b via the unified ordinal engine.
5962
- // Huge coefficients (> MSI / ordinal args) supremum-collapse:
5963
- // ω^i*HUGE ≈ ω^(i+1) with all lower coefficients swallowed, e.g.
5964
- // 4{ω*5+X}2 = 4{ω*6}X (X huge) → X plus one ω*6 row;
5965
- // 4{ω*X+3}2 = 4{ω^2}X → X plus one ω^2 row.
5966
- // The result anchors at the largest operand (the huge argument's value).
6050
+ // Ordinal BEAF computation for 4+ arguments: BEAF(a,b,c,d,...) =
6051
+ // a{...+ω*d+c}b via the unified ordinal engine. Huge coefficients (> MSI /
6052
+ // ordinal args) supremum-collapse (ω^i*HUGE ≈ ω^(i+1), lower coefficients
6053
+ // swallowed): 4{ω*5+X}2 = 4{ω*6}X, 4{ω*X+3}2 = 4{ω^2}X. The result anchors
6054
+ // at the largest operand.
5967
6055
  Q._beafOrdinal = function(a, b, coeffs, hugeArgs) {
5968
6056
  a = new MetaNum(a);
5969
6057
  b = new MetaNum(b);
@@ -5991,18 +6079,12 @@
5991
6079
  };
5992
6080
 
5993
6081
  // ==================== Hardy Hierarchy ====================
5994
- // H_α(n) via transfinite recursion (issues.md / README):
5995
- // H_0(n) = n
5996
- // H_{α+1}(n) = H_α(n+1) (successor step: only +1, never iterated)
5997
- // H_λ(n) = H_{λ[n]}(n) (limit step: CNF fundamental sequence at n)
5998
- // where λ[n] acts on the lowest limit term: (… + ω^j·c_j)[n] = … + ω^j·(c_j−1)
5999
- // + ω^{j−1}·n. Closed forms keep the recursion finite:
6000
- // H_{β+c}(n) = H_β(n+c) (c successor steps)
6001
- // H_{β+ω·c}(n) = H_β(n·2^c) (c ω-level limit steps)
6002
- // For ω^j·c segments with c beyond the exact-iteration bound (j ≥ 2) the
6003
- // value collapses into the hyperoperation engine, mirroring the classic
6004
- // identity F_j = H^{ω^j} (F_2(n)=n·2^n, F_3(n)≈2↑↑n, …):
6005
- // H_{β+ω^j·c}(n) ≈ H_β(2{c}^j) i.e. 2.arrow(j)(c)
6082
+ // H_α(n) by transfinite recursion: H_0(n)=n, H_{α+1}(n)=H_α(n+1),
6083
+ // H_λ(n)=H_{λ[n]}(n), where λ[n] hits the lowest limit term
6084
+ // (…+ω^j·c_j)[n] = …+ω^j·(c_j−1)+ω^{j−1}·n. Closed forms keep it finite:
6085
+ // H_{β+c}(n) = H_β(n+c); H_{β+ω·c}(n) = H_β(n·2^c).
6086
+ // Beyond the exact-iteration bound (j ≥ 2) an ω^j·c segment collapses into
6087
+ // the hyperoperation engine (F_j = H^{ω^j}): H_{β+ω^j·c}(n) ≈ H_β(2{c}^j).
6006
6088
  var HARDY_EXACT_BOUND = 50;
6007
6089
  // H_α(n) — ITERATIVE (the original tail recursion grew hundreds of frames
6008
6090
  // deep for inputs like hardy(1e10+20) where n1≈40 makes every ω^j segment
@@ -6049,12 +6131,11 @@
6049
6131
  continue;
6050
6132
  }
6051
6133
  if (j >= c.length) return n; // no positive term left (safety net)
6052
- // A coefficient can turn FRACTIONAL because the fundamental-sequence step
6053
- // writes the running base n — and n is 10+f for a fractional hardy input
6054
- // (hardy(1000.5)). For 0 < c_j < 1 the "-1" step would go negative and
6055
- // leave no positive term at all, so take the PARTIAL step instead:
6056
- // ω^j·f contributes ω^(j-1)·(n·f) (continuous — f→1 is the full
6057
- // ω^(j-1)·n step of the integer recursion, f→0 contributes nothing)
6134
+ // A coefficient can turn FRACTIONAL because the FS step writes the
6135
+ // running base n (n = 10+f for a fractional hardy input). For
6136
+ // 0 < c_j < 1 the "-1" step would go negative, so take the PARTIAL step:
6137
+ // ω^j·f contributes ω^(j-1)·(n·f) — continuous, f→1 is the full
6138
+ // ω^(j-1)·n step and f→0 contributes nothing.
6058
6139
  var cjN = c[j].toNumber();
6059
6140
  if (isFinite(cjN) && cjN > 0 && cjN < 1 && j >= 2) {
6060
6141
  c[j] = MetaNum.ZERO.clone();
@@ -6080,17 +6161,13 @@
6080
6161
  } finally { _skipCanon--; }
6081
6162
  };
6082
6163
 
6083
- // H_{ω^k}(n) for the from-below base of hardy (n ≥ 1e10).
6084
- // The exact expansion writes a tower of level k-1 — H_{ω^10}(10) =
6085
- // 10{9}(11…21), H_{ω^20}(20) = 10{19}(21…22) — so array[0] holds k entries
6086
- // and the step-by-step expansion only fits while k ≤ maxCols. Above that
6087
- // the running base turns structured, the coefficients the limit steps write
6088
- // from it turn structured too, and every later comparison / collapse becomes
6089
- // meaningless: hardy(1e10+11) (k = n1 = 22) collapsed to [[1],[2,20]] — a
6090
- // destroyed base with a bogus row — and hardy(1e16+1e13) (k = 28) likewise.
6091
- // There the from-below value is taken from the engine instead: 10{k-1}(n+1)
6092
- // is exactly the lower bound the exact expansion stays strictly above, so
6093
- // hardy stays monotone and keeps its "strictly below the engine" property.
6164
+ // H_{ω^k}(n), the from-below base of hardy (n ≥ 1e10). The exact expansion
6165
+ // writes a tower of level k-1 (H_{ω^10}(10) = 10{9}(11…21)), so array[0]
6166
+ // holds k entries and only fits while k ≤ maxCols. Above that the running
6167
+ // base and the coefficients the limit steps write from it turn structured and
6168
+ // every later comparison/collapse is meaningless (hardy(1e10+11) collapsed to
6169
+ // [[1],[2,20]]), so the value is taken from the engine instead:
6170
+ // 10{k-1}(n+1) is exactly the lower bound the exact expansion stays above.
6094
6171
  Q._hardyOmegaPower = function (n1) {
6095
6172
  var n1Num = (n1.layer === 0 && n1.array.length === 1 && n1.array[0].length === 1) ? n1.toNumber() : Infinity;
6096
6173
  if (isFinite(n1Num) && n1Num >= 2) {
@@ -6106,14 +6183,11 @@
6106
6183
  ec.push(1);
6107
6184
  return Q._hardyH(ec, n1);
6108
6185
  }
6109
- // n1 > maxCols+1: the exact tower [c0, (n1-1)×(n1-2)] no longer fits the
6110
- // array (22 entries for n1 = 22, maxCols = 20). Keep the TRUNCATED
6111
- // cascade instead of the engine value 10{n1-1}(n1+1): the tower level
6112
- // n1-1 over the definitional base — hardy("1e10+11") =
6113
- // [3086.036…, 21×19] (the user-visible [非整数, 21, 21, …, 21] shape),
6114
- // strictly above hardy("1e10+10")'s exact [6313063, 19×18] (the level 21
6115
- // dominates the level 19) and still far below the matching engine
6116
- // ordinal op 10{ω^ω+ω+1}10.
6186
+ // n1 > maxCols+1: the exact tower [c0, (n1-1)×(n1-2)] no longer fits
6187
+ // (22 entries for n1 = 22). Keep the TRUNCATED cascade (level n1-1 over
6188
+ // the definitional base) instead of 10{n1-1}(n1+1): hardy("1e10+11") =
6189
+ // [3086.036…, 21×19] — strictly above hardy("1e10+10")'s exact
6190
+ // [6313063, 19×18] and far below 10{ω^ω+ω+1}10.
6117
6191
  var lv = Math.floor(n1Num) - 1;
6118
6192
  var depth = Math.min(Math.floor(n1Num) - 2, MetaNum.maxCols - 1);
6119
6193
  var r0 = Q._hardyBaseR0();
@@ -6127,12 +6201,10 @@
6127
6201
  return Q._applyOrdinalRows(n1, [0, 1], 1);
6128
6202
  };
6129
6203
 
6130
- // Decimal digit string of a plain number stored as r0 = [v, 1] (= 10^v),
6131
- // or null when the value is not in that form / has no finite exponent.
6132
- // Only an actual POWER TOWER is excluded: 10^^k has the same r0 shape but
6133
- // v ≥ 1e10, so "1e100000" (= 10^100000, v = 100000) is a plain number and
6134
- // keeps the ordinary digit path — the old guard rejected exponents above
6135
- // 1e5 and pushed hardy("1e100000") into the tower branch (layer 1).
6204
+ // Decimal digit string of a plain number stored as r0 = [v, 1] (= 10^v), or
6205
+ // null when the value is not in that form. Only an actual POWER TOWER is
6206
+ // excluded (10^^k has the same shape but v ≥ 1e10), so "1e100000" keeps the
6207
+ // ordinary digit path — the old guard pushed it into the tower branch.
6136
6208
  Q._hardyDigitsOfPowForm = function (r0) {
6137
6209
  if (!r0 || r0.length !== 2 || r0[1] !== 1 || !isFinite(r0[0])) return null;
6138
6210
  if (r0[0] >= 1e10) return null; // power tower → slog branch
@@ -6170,11 +6242,123 @@
6170
6242
  return v;
6171
6243
  };
6172
6244
 
6173
- // MetaNum.hardy(n): the Hardy level of n.
6245
+ // hardy(n, base): H_α(base), where α is built from the base-`base` digits of
6246
+ // n (hardy(1234) = H_{ω³+ω²·2+ω·3+4}(10); hardy(10,8) = H_{ω+2}(8) = 20
6247
+ // because "10" reads as "12" in base 8). base defaults to 10 and must be an
6248
+ // integer in [2, 1000]. The base-10 path is the historical implementation;
6249
+ // other bases read the same ordinal off their own digit expansion.
6250
+ Q.hardy = function (n, base) {
6251
+ var b = hardyBase(base);
6252
+ if (b === 10) return Q._hardyDecimal(n);
6253
+ return Q._hardyBased(n, b);
6254
+ };
6255
+
6256
+ // Base argument validation (undefined → the default 10).
6257
+ function hardyBase(base) {
6258
+ if (base === undefined || base === null) return 10;
6259
+ var b = (base instanceof MetaNum) ? base.toNumber() : base;
6260
+ if (typeof b !== 'number' || !isFinite(b) || b !== Math.floor(b) || b < 2 || b > 1000) {
6261
+ throw Error(metaNumError + 'hardy: base must be an integer in [2, 1000]');
6262
+ }
6263
+ return b;
6264
+ }
6265
+
6266
+ // FGH(x, y) = H_{y^x}(y): the fast-growing hierarchy entry, defined through
6267
+ // hardy (f_x(y) with the hereditary base-y reading of y^x).
6268
+ Q.fgh = function (x, y) {
6269
+ var b = hardyBase(y);
6270
+ x = new MetaNum(x);
6271
+ if (x.isNaN()) return MetaNum.NaN.clone();
6272
+ var arg = new MetaNum(b).pow(x);
6273
+ return Q._hardyBased(arg, b);
6274
+ };
6275
+
6276
+ // Little-endian CNF coefficients of the base-b expansion of a decimal digit
6277
+ // string (most significant first), or null past the digit budget. Repeated
6278
+ // division on the digit string keeps values beyond the double range exact.
6279
+ function hardyBaseCoeffs(decStr, b) {
6280
+ if (b === 10) {
6281
+ var c10 = [];
6282
+ for (var i = decStr.length - 1; i >= 0; i--) c10.push(decStr.charCodeAt(i) - 48);
6283
+ return c10;
6284
+ }
6285
+ var coeffs = [];
6286
+ var cur = decStr.replace(/^0+/, '');
6287
+ if (cur === '') cur = '0';
6288
+ var guard = 0;
6289
+ while (cur !== '0') {
6290
+ if (++guard > 100000 || coeffs.length > 100000) return null;
6291
+ var q = '';
6292
+ var rem = 0;
6293
+ for (var i = 0; i < cur.length; i++) {
6294
+ var acc = rem * 10 + (cur.charCodeAt(i) - 48);
6295
+ var d = Math.floor(acc / b);
6296
+ rem = acc - d * b;
6297
+ q += String.fromCharCode(48 + d);
6298
+ }
6299
+ cur = q.replace(/^0+/, '') || '0';
6300
+ coeffs.push(rem);
6301
+ }
6302
+ return coeffs;
6303
+ }
6304
+
6305
+ // hardy(n, base) for base ≠ 10: the ordinal is read off the base-`base`
6306
+ // digits of n and evaluated on the argument `base` (+ any fraction of n).
6307
+ // Plain finite inputs only — structured / tower inputs keep the base-10
6308
+ // shadowing, which is decimal-specific.
6309
+ Q._hardyBased = function (n, b) {
6310
+ var rawNum = (typeof n === 'number') ? n
6311
+ : (typeof n === 'string' ? Number(n) : null);
6312
+ if (typeof n === 'string' && n.indexOf('+') > 0) {
6313
+ var plusParts = n.split('+');
6314
+ if (plusParts.length === 2 && plusParts[0] !== '' && plusParts[1] !== '' &&
6315
+ !/[eE]$/.test(plusParts[0]) && !/[eE]$/.test(plusParts[1])) {
6316
+ var pvA = new MetaNum(plusParts[0].trim());
6317
+ var pvB = new MetaNum(plusParts[1].trim());
6318
+ if (!pvA.isNaN() && !pvB.isNaN()) { n = pvA.add(pvB); rawNum = null; }
6319
+ }
6320
+ }
6321
+ if (rawNum !== null && !isFinite(rawNum)) rawNum = null;
6322
+ n = new MetaNum(n);
6323
+ if (n.sign !== 1) {
6324
+ throw Error(metaNumError + 'hardy: n must be a non-negative integer');
6325
+ }
6326
+ var num = (rawNum !== null) ? rawNum
6327
+ : ((n.layer === 0 && n.array.length === 1) ? n.toNumber() : Infinity);
6328
+ var hStr = (rawNum === null && n.layer === 0 && n.array.length === 1)
6329
+ ? Q._hardyDigitsOfPowForm(n.array[0]) : null;
6330
+ if (!isFinite(num)) {
6331
+ if (n.layer === 0 && n.array.length === 1 && hStr !== null) {
6332
+ // a plain number beyond the double range: its exact digits
6333
+ } else {
6334
+ throw Error(metaNumError + 'hardy: base != 10 supports plain finite inputs only');
6335
+ }
6336
+ }
6337
+ var s = (hStr !== null) ? hStr : String(num);
6338
+ var eMatch = s.match(/^(\d)(?:\.(\d+))?e\+?(\d+)$/);
6339
+ if (eMatch) {
6340
+ var eFrac = eMatch[2] || '';
6341
+ var eZeros = Number(eMatch[3]) - eFrac.length;
6342
+ if (eZeros > 0) s = eMatch[1] + eFrac + '0'.repeat(eZeros);
6343
+ }
6344
+ var hFrac = 0;
6345
+ var hDot = s.indexOf('.');
6346
+ if (hDot >= 0) {
6347
+ hFrac = Number('0.' + s.slice(hDot + 1));
6348
+ s = s.slice(0, hDot);
6349
+ }
6350
+ var coeffs = hardyBaseCoeffs(s, b);
6351
+ if (coeffs === null) {
6352
+ throw Error(metaNumError + 'hardy: base expansion exceeds the digit budget');
6353
+ }
6354
+ return Q._hardyH(coeffs, new MetaNum(b + hFrac));
6355
+ };
6356
+
6357
+ // MetaNum.hardy(n): the Hardy level of n (base 10).
6174
6358
  // n < 10 → 10 + n; otherwise the decimal digits of n become the CNF
6175
6359
  // coefficients of an ordinal α (hardy(1234) = H_{ω³+ω²·2+ω·3+4}(10)) and
6176
6360
  // the result is H_α(10).
6177
- Q.hardy = function (n) {
6361
+ Q._hardyDecimal = function (n) {
6178
6362
  // A plain JS number / numeric string keeps its own decimal expansion: from
6179
6363
  // 1e16 on the library stores the value as 10^v (r0 = [v,1]) and the way
6180
6364
  // back through the double loses the low digits — hardy(1e16+1e13) =
@@ -6233,25 +6417,18 @@
6233
6417
  var hNum = hVal.toNumber();
6234
6418
  if (isFinite(hNum) && hNum >= 2 && hNum <= Number.MAX_SAFE_INTEGER) {
6235
6419
  // k ≤ MSI: the tower fits the engine limit (f_ε₀); k > MSI is
6236
- // beyond ε₀ and the Hardy hierarchy is undefined there → Infinity.
6237
- // The ordinal is read off the value itself: V = 10^W gives
6238
- // α = ω^ord(W), so the result is the ordinary cascade on the
6239
- // from-below base while the tower height still leaves a readable
6240
- // exponent (k ≤ 3 — hardy(ee10) = H_{ω^(ω^ω)}(10) = the ω^ω
6241
- // cascade, layer 0 like iterate(10), not a layer-2 marker).
6242
- // Above that the level no longer fits into ordinal rows and the
6243
- // value becomes a layer marker whose layer is ceil(k) - 3:
6244
- // ee10 < 10^(1e10+1) < ee20 … eee10 → layer 1
6245
- // eee20 … eeee10 → layer 2, and so on
6420
+ // beyond ε₀, where the Hardy hierarchy is undefined → Infinity.
6421
+ // The ordinal is read off the value itself (V = 10^W gives
6422
+ // α = ω^ord(W)): while the height leaves a readable exponent the
6423
+ // result is the ordinary cascade on the from-below base (hardy(ee10)
6424
+ // = the ω^ω cascade, layer 0); above that it becomes a layer marker
6425
+ // of layer ceil(k)-3 (ee20 … eee10 → 1, eee20 … → 2, …).
6246
6426
  var r0T = n.array[0];
6247
- // v2.0.2 (issues): clean power towers — EVERY extra 10^ level in
6248
- // the input raises hardy's layer by ONE, the ordinal rows stay
6249
- // those of the innermost readable expansion:
6250
- // hardy("1e308") = the layer-0 digit-path cascade (…[8,6,0,3],[8,7,0,3])
6251
- // hardy("e1e308") = the same rows at layer 1
6252
- // hardy("ee1e308") = the same rows at layer 2, and so on.
6253
- // The stored tower r0 = [v, k] is (k-1) further 10^ levels over
6254
- // 10^v; a layer-L input adds L more levels on top.
6427
+ // Clean power towers: every extra 10^ level in the input raises
6428
+ // hardy's layer by ONE, the rows stay those of the innermost
6429
+ // readable expansion (hardy("1e308") = the layer-0 cascade,
6430
+ // hardy("e1e308") = the same rows at layer 1, …). The stored tower
6431
+ // r0 = [v, k] is (k-1) levels over 10^v; layer L adds L more.
6255
6432
  if (r0T && r0T.length === 2 && r0T[1] >= 1 &&
6256
6433
  r0T[1] === Math.floor(r0T[1]) &&
6257
6434
  isFinite(r0T[0]) && r0T[0] >= 10 &&
@@ -6330,30 +6507,31 @@
6330
6507
  }
6331
6508
  var hArg = hFrac > 0 ? new MetaNum(10 + hFrac) : MetaNum.TEN.clone();
6332
6509
  if (s.length >= 11) {
6333
- // n ≥ 1e10 (issues.md v2.0): the ordinal is built per definition, then
6334
- // evaluated from below on the engine's own representation:
6335
- // n = dk·10^kExp + rest → α = ω^ord(kExp)·dk + ord(rest)
6336
- // H_α(10) = H_{ω^ord(kExp)·dk}(H_ord(rest)(10)) — the lower part acts
6337
- // first: n1 = H_ord(rest)(10) (recursive, exact path for rest < 1e10).
6338
- // n1 = H_rest(10) becomes the fundamental-sequence argument of the
6339
- // leading term:
6340
- // kExp = 10 (ord = ω): H_{ω^ω·dk}(n1) = H_{ω^n1}(n1) exact (first
6341
- // segment), the remaining dk−1 ω^ω-segments each add one ω-row —
6342
- // hardy(1e10) = H_{ω^10}(10) = [3086.036065328153, 9×8] EXACTLY,
6343
- // strictly below 10{10}10 (issues.md);
6344
- // kExp ≥ 11 (ord = ω+c): mirror the engine's own ordinal rows for
6345
- // 10{ω+c}(9+dk) on the from-below base H_{ω^n1}(n1) — hardy(1e11)
6346
- // = H_{ω^(ω+1)}(10) keeps expande(10,10)'s row structure with the
6347
- // strictly smaller definitional base, so hardy(1e11) < 10{ω+1}10
6348
- // (issues.md).
6510
+ // n ≥ 1e10: n = dk·10^kExp + rest → α = ω^ord(kExp)·dk + ord(rest), and
6511
+ // H_α(10) = H_{ω^ord(kExp)·dk}(H_ord(rest)(10)) — the lower part acts
6512
+ // first (n1 = H_rest(10), recursive for rest < 1e10) and then becomes the
6513
+ // fundamental-sequence argument of the leading term. kExp = 10 (ord ω):
6514
+ // hardy(1e10) = H_{ω^10}(10) = [3086.036065328153, 9×8] exactly; kExp ≥ 11
6515
+ // mirrors the engine's 10{ω+c}(9+dk) rows on the smaller definitional
6516
+ // base, so hardy(1e11) < 10{ω+1}10.
6349
6517
  var kExp = s.length - 1;
6350
6518
  var dk = s.charCodeAt(0) - 48;
6351
- var restNum = Number(s.slice(1));
6519
+ var restStr = s.slice(1);
6520
+ var restNum = Number(restStr);
6352
6521
  var n1 = hArg.clone();
6353
6522
  // the fractional part flows into the rest part too: hardy("1e10+1.5")
6354
6523
  // = H_{ω^10}(hardy(1.5)) = H_{ω^10}(11.5) — dropping the fraction here
6355
6524
  // made every 1e10+k.f input behave like 1e10+k
6356
- if (restNum > 0) n1 = Q.hardy(restNum + hFrac);
6525
+ if (isFinite(restNum) && restNum > 0) n1 = Q.hardy(restNum + hFrac);
6526
+ else if (/[1-9]/.test(restStr)) {
6527
+ // issue #17: the rest itself can exceed the double range — hardy("1.5e309")
6528
+ // has rest = 5e308 > Number.MAX_VALUE, so Number() overflowed to Infinity
6529
+ // and hardy(Infinity) collapsed the whole value to Infinity (integer
6530
+ // mantissas like hardy("1e309") kept working because their rest is 0).
6531
+ // Recurse on the EXACT digit string instead: MetaNum parses it into the
6532
+ // 10^v form and the digit path below reads it back exactly.
6533
+ n1 = Q.hardy(new MetaNum(restStr));
6534
+ }
6357
6535
  return Q._hardyLeading(kExp, dk, n1);
6358
6536
  }
6359
6537
  if (num < 10) return new MetaNum(10 + num);
@@ -6362,8 +6540,8 @@
6362
6540
  return Q._hardyH(coeffs, hArg);
6363
6541
  };
6364
6542
 
6365
- // The leading term ω^ord(kExp)·dk of hardy's ordinal, evaluated from below
6366
- // on the already-computed lower part n1 = H_ord(rest)(10).
6543
+ // The leading term ω^ord(kExp)·dk of hardy's ordinal, evaluated from below on
6544
+ // the already-computed lower part n1 = H_ord(rest)(10).
6367
6545
  Q._hardyLeading = function (kExp, dk, n1) {
6368
6546
  // a plain operand still has a single plain number as its whole array[0]
6369
6547
  var nPlain = (n1.layer === 0 && n1.array.length === 1 && n1.array[0].length === 1);
@@ -6374,24 +6552,25 @@
6374
6552
  return Q._hardyKeepBase(
6375
6553
  Q._applyOrdinalRows(Q._hardyOmegaPower(n1), [0, 1], dk - 1)).normalize();
6376
6554
  }
6377
- // kExp ≥ 11 (ord = ω+c): β = ord(kExp) and the leading term ω^β·dk is dk
6378
- // APPLICATIONS of H_{ω^β}, one after the other on the running value:
6379
- // hardy(1.1e11) = H_{ω^(ω+1)+ω^ω}(10) = H_{ω^(ω+1)}(H_{ω^ω}(10))
6380
- // = [3086.036,9×8] [1,1,1] (one row per application)
6381
- // hardy(2e11) = H_{ω^(ω+1)·2}(10) = H_{ω^(ω+1)}(H_{ω^(ω+1)}(10))
6382
- // = [3086.036,9×8] [8,0,1] [1,1,1]
6383
- // hardy(1e16+1e13) = H_{ω^(ω+6)}(H_{ω^(ω+3)}(10)) → … [1,6,1]
6384
- // so an application is a row [1, β] — never a bump of the ω-row count
6385
- // ([9,0,1] / [16,0,1] conflated dk with the rest-part). The FIRST
6386
- // application on a plain operand is still expanded from below: the base
6387
- // H_{ω^n1}(n1) plus the cascade of 10{β}10 (hardy(1e11) = [3086.036,9×8]
6388
- // [8,0,1], strictly below 10{ω+1}10 — issues.md).
6389
- var ks = String(kExp);
6555
+ // kExp ≥ 11: β = ord(kExp) and ω^β·dk is dk APPLICATIONS of H_{ω^β}, one
6556
+ // row [1, β] each (hardy(1.1e11) = [3086.036,9×8] [1,1,1]). The first
6557
+ // application on a plain operand expands from below (base H_{ω^n1}(n1)
6558
+ // plus the 10{β}10 cascade), strictly below 10{ω+1}10.
6559
+ // kExp may be non-integer (the tower branch passes 10^9.05 = 1122018454.3):
6560
+ // only the integer digits spell the ordinal, the fraction raises the
6561
+ // from-below base — reading String(kExp) verbatim put the decimal POINT
6562
+ // into the row (charCode('.')-48 = -2) and inflated it to one column per
6563
+ // character (issue #15: hardy("ee9.05")).
6564
+ var kInt = Math.floor(kExp);
6565
+ var kFracH = kExp - kInt;
6566
+ var ks = String(kInt);
6390
6567
  var ordCoeffs = [];
6391
6568
  for (var oi = ks.length - 1; oi >= 0; oi--) ordCoeffs.push(ks.charCodeAt(oi) - 48);
6392
6569
  var out, extra;
6393
6570
  if (nPlain && isFinite(n1Num) && n1Num >= 2) {
6394
- out = Q._hardyOmegaPower(n1);
6571
+ // the fractional part of kExp raises the from-below base (10+f)
6572
+ var baseN1 = (kFracH > 1e-12) ? n1.add(new MetaNum(Number(kFracH.toPrecision(15)))) : n1;
6573
+ out = Q._hardyOmegaPower(baseN1);
6395
6574
  var mir = Q._hyperopFromOrdinalRaw(MetaNum.TEN.clone(), MetaNum.TEN.clone(), ordCoeffs);
6396
6575
  for (var ri = 1; ri < mir.array.length; ri++) {
6397
6576
  out = Q._applyOrdinalRows(out, mir.array[ri].slice(1), mir.array[ri][0]);
@@ -6408,8 +6587,7 @@
6408
6587
  };
6409
6588
 
6410
6589
  // ==================== BEAF Array Notation ====================
6411
- // Bowers' Exploding Array Function: https://googology.fandom.com/wiki/Array_notation
6412
- // Rules:
6590
+ // Bowers' Exploding Array Function (googology.fandom.com/wiki/Array_notation):
6413
6591
  // 1. {a} = a, {a,b} = a^b
6414
6592
  // 2. {a,b,c,...,n,1} = {a,b,c,...,n}
6415
6593
  // 3. {a,1,b,c,...,n} = a
@@ -6498,14 +6676,20 @@
6498
6676
  };
6499
6677
 
6500
6678
  // Parse BEAF string: {a,b,c,...}
6679
+ // Also accepts the sign/reciprocal spellings toBeaf() emits (issue #21):
6680
+ // "-{5}" (negative) and "{10,320}⁻¹" (sub-unit).
6501
6681
  Q.fromBeaf = function(str) {
6502
6682
  if (typeof str !== 'string') return MetaNum.NaN.clone();
6503
6683
  var s = str.trim();
6684
+ var negate = false;
6685
+ if (s.charAt(0) === '-') { negate = true; s = s.slice(1).trim(); }
6686
+ var reciprocal = false;
6687
+ if (s.slice(-2) === '\u207B\u00B9') { reciprocal = true; s = s.slice(0, -2).trim(); }
6504
6688
  if (s.charAt(0) !== '{' || s.charAt(s.length - 1) !== '}') {
6505
6689
  return MetaNum.NaN.clone();
6506
6690
  }
6507
6691
  var inner = s.slice(1, -1).trim();
6508
- if (inner === '') return MetaNum.ONE.clone();
6692
+ if (inner === '') return MetaNum.NaN.clone();
6509
6693
  var parts = inner.split(',');
6510
6694
  var args = [];
6511
6695
  for (var i = 0; i < parts.length; i++) {
@@ -6513,44 +6697,82 @@
6513
6697
  if (!isFinite(val) || val < 1) return MetaNum.NaN.clone();
6514
6698
  args.push(val);
6515
6699
  }
6516
- return Q.BEAF.apply(null, args);
6517
- };
6700
+ var out = Q.BEAF.apply(null, args);
6701
+ if (reciprocal) out = out.rec();
6702
+ if (negate) out = out.neg();
6703
+ return out;
6704
+ };
6705
+
6706
+ // The integer !Aa<n> = 10{ω^n}10 (issue #19: "!" adds one ω^ to the level).
6707
+ // While the ω^n expansion fits the row budget — the cascade's top row
6708
+ // [8, 9×n] needs n+1 ≤ maxCols columns — store the full rule-3 cascade at
6709
+ // `layer` (0 for "!", 1 for "@", …). Past the budget the cascade would
6710
+ // silently truncate ω^n down to ω^(maxCols-1), so instead go ONE LAYER UP
6711
+ // and keep the de-!-ed compact [[n],[1,0,1]] — the de-layer rule's
6712
+ // over-budget form, which preserves n in r0 (e.g. !Aa300).
6713
+ function bangAaInteger(n, layer) {
6714
+ if (n + 1 <= MetaNum.maxCols) {
6715
+ var coeffs = [];
6716
+ for (var i = 0; i < n; i++) coeffs.push(0);
6717
+ coeffs.push(1);
6718
+ var v = Q._hyperopFromOrdinalRaw(MetaNum.TEN.clone(), MetaNum.TEN.clone(), coeffs);
6719
+ v.layer = layer || 0;
6720
+ return v;
6721
+ }
6722
+ return new MetaNum({ sign: 1, layer: (layer || 0) + 1, array: [[n], [1, 0, 1]] });
6723
+ }
6724
+
6725
+ // Build the error thrown when a value has no faithful BEAF text form.
6726
+ function unrepresentableToBeaf(x) { var err = new Error(metaNumError + 'toBeaf: value has no BEAF representation ' +
6727
+ '(multi-row / layered internal form cannot be encoded as {a,b,...})');
6728
+ err.name = 'MetaNumUnrepresentableError';
6729
+ err.code = 'METANUM_UNREPRESENTABLE';
6730
+ return err;
6731
+ }
6518
6732
 
6519
6733
  // Convert to BEAF string: {a,b,c,...}
6520
6734
  P.toBeaf = function() {
6521
6735
  var x = this.clone().normalize();
6522
6736
  if (x.isNaN()) return 'NaN';
6737
+ // issue #21: a negative value keeps its sign — "-" prefixed to the BEAF of
6738
+ // its magnitude — instead of silently dropping it (MetaNum(-5) used to
6739
+ // come back as "{5}"). sign -2 is the negative sub-unit case, which the
6740
+ // recursive call spells as "-{…}⁻¹".
6741
+ if (x.sign === -1 || x.sign === -2) {
6742
+ var pos = x.clone();
6743
+ pos.sign = (x.sign === -1) ? 1 : 2;
6744
+ return '-' + pos.toBeaf();
6745
+ }
6746
+ // issue #21: a sub-unit value (sign 2 — r0 holds the RECIPROCAL) spells the
6747
+ // BEAF of the value it represents with a "⁻¹" suffix:
6748
+ // MetaNum("1e-320") → "{10,320}⁻¹" (reciprocal 10^320 = {10,320})
6749
+ // MetaNum("0.001") → "{1000}⁻¹" (reciprocal 1000 < MSI)
6750
+ // instead of dropping the sign and printing the bare reciprocal.
6751
+ var suffix = '';
6752
+ if (x.sign === 2) {
6753
+ if (!(x.layer === 0 && x.array.length === 1)) throw unrepresentableToBeaf(x);
6754
+ suffix = '\u207B\u00B9';
6755
+ x = x.rec();
6756
+ }
6523
6757
  if (x.layer === 0 && x.array.length === 1) {
6524
6758
  if (x.eq(MetaNum.ZERO)) return '{0}';
6525
- return '{' + decimalPlaces(x.array[0][0], 6) + '}';
6526
- }
6527
- if (x.layer > 0 || x.array.length > 1) {
6528
- if (x.array.length === 2 && x.array[1].length >= 3) {
6529
- var row = x.array[1];
6530
- var diag = row[row.length - 1];
6531
- if (diag === 1 && row[0] === 1) {
6532
- var vals = row.slice(1, row.length - 1);
6533
- var allNonNegative = true;
6534
- for (var i = 0; i < vals.length; i++) {
6535
- if (vals[i] < 0) { allNonNegative = false; break; }
6536
- }
6537
- if (allNonNegative) {
6538
- var a = decimalPlaces(x.array[0][0], 6);
6539
- // Reconstruct BEAF: {a, ?, c, d, e, ...} from ordinal row [1, c, d, e, ..., 1]
6540
- // (issues.md convention: BEAF(a,b,c,d,...) = a{...+ω*(d-1)+c}b)
6541
- var beafParts = [a, '?'];
6542
- for (var i = 0; i < vals.length; i++) {
6543
- beafParts.push(String(vals[i]));
6544
- }
6545
- beafParts.push(String(diag));
6546
- return '{' + beafParts.join(', ') + '}';
6547
- }
6548
- }
6759
+ var r0 = x.array[0];
6760
+ // [e, 1] is exactly 10^e = BEAF {10, e}. Keep the base instead of
6761
+ // dropping it and emitting the bare exponent (issue #17 D02:
6762
+ // BEAF(10,16) used to come back as "{16}"). Only a positive value with a
6763
+ // round-trippable argument (e >= 1) is encoded this way; everything else
6764
+ // keeps the historical decimal approximation of the leading term.
6765
+ if (x.sign === 1 && r0.length === 2 && r0[1] === 1 &&
6766
+ typeof r0[0] === 'number' && isFinite(r0[0]) && r0[0] >= 1) {
6767
+ return '{10,' + decimalPlaces(r0[0], 6) + '}' + suffix;
6549
6768
  }
6769
+ return '{' + decimalPlaces(r0[0], 6) + '}' + suffix;
6550
6770
  }
6551
- return '{' + x.array.map(function(r) {
6552
- return '[' + r.map(function(v) { return decimalPlaces(v, 6); }).join(', ') + ']';
6553
- }).join(', ') + '}';
6771
+ // A multi-row / layered value has no faithful BEAF text: the ordinal-row
6772
+ // form does not determine the BEAF iteration count `b`, and dumping the
6773
+ // internal rows is never acceptable output (issue #17 D03). Fail loudly
6774
+ // instead of emitting `[...]` literals or a placeholder `?` argument.
6775
+ throw unrepresentableToBeaf(x);
6554
6776
  };
6555
6777
 
6556
6778
 
@@ -6815,14 +7037,11 @@
6815
7037
  MetaNum = clone(MetaNum);
6816
7038
  MetaNum = defineConstants(MetaNum);
6817
7039
 
6818
- // Sub-unit canonical form: run the engine's structural CONSUMERS with it off.
6819
- // These functions read r0 as a plain magnitude and chain through log10/exp
6820
- // (whose results are now canonicalized when a user calls them directly), so
6821
- // without this they saw reciprocals where they expected values — gamma(0.5)
6822
- // read r0 [2] as 2, slog computed from a 3.32 instead of 0.301, and
6823
- // layeradd/pentate_log returned garbage. The PRODUCERS (constructor with a
6824
- // primitive, add/sub/mul/div, log10, ln, exp, root, neg) stay canonicalized,
6825
- // so MetaNum(0.5).sign === 2 and arithmetic results in (0,1) carry sign 2.
7040
+ // Sub-unit canonical form: the engine's structural CONSUMERS (gamma, slog,
7041
+ // layeradd, pentate_log, …) read r0 as a plain magnitude, so they run with it
7042
+ // off — otherwise they saw reciprocals where they expected values (gamma(0.5)
7043
+ // read r0 [2] as 2). The PRODUCERS (constructor, arithmetic, log10/ln/exp,
7044
+ // root, neg) stay canonicalized, so MetaNum(0.5).sign === 2.
6826
7045
  (function () {
6827
7046
  var rawConsumers = [
6828
7047
  'gamma', 'lambertw', 'slog', 'layeradd', 'layeradd10',