@danielsimonjr/mathts-functions 0.59.0 → 0.60.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.
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Layer 1 rational-function symbolic integration — Task 1: parse a
3
+ * single-variable rational-function expression into exact integer
4
+ * numerator/denominator polynomials, split off the polynomial part via
5
+ * exact-ℚ long division, and integrate a polynomial termwise (power rule).
6
+ *
7
+ * Reuses the univariate expression parser (`polyFromExpression`, from the
8
+ * Gröbner-basis module) for parsing and the bigint dense-polynomial
9
+ * convention (`IntPoly`, index = degree) from the #7 factorization engine
10
+ * for the integer representation.
11
+ *
12
+ * See docs/superpowers/plans/2026-07-20-risch-layer1-rational-integration.md
13
+ * (Task 1). Later tasks build denominator factorization, exact-ℚ partial
14
+ * fractions, and per-factor closed-form integration on top of this module.
15
+ */
16
+ import { type IntPoly } from '../typed/factorization/integer-poly.js';
17
+ /** Exact rational number, always normalized to lowest terms with a positive denominator. */
18
+ export interface Rat {
19
+ num: bigint;
20
+ den: bigint;
21
+ }
22
+ /** A rational function `numer(x)/denom(x)` with integer dense (`IntPoly`) coefficients. */
23
+ export interface RatFunc {
24
+ numer: IntPoly;
25
+ denom: IntPoly;
26
+ }
27
+ export declare function ratAdd(a: Rat, b: Rat): Rat;
28
+ export declare function ratSub(a: Rat, b: Rat): Rat;
29
+ export declare function ratMul(a: Rat, b: Rat): Rat;
30
+ export declare function ratDiv(a: Rat, b: Rat): Rat;
31
+ export declare function ratFromBigint(n: bigint): Rat;
32
+ /**
33
+ * Parses a single-variable expression `numerExpr/denomExpr` (or a bare
34
+ * polynomial, denominator `[1n]`) into integer numerator/denominator dense
35
+ * polynomials. Rational coefficients are cleared by the LCM of their
36
+ * denominators (numerator and denominator are each cleared independently,
37
+ * then cross-scaled by the other's factor so the represented ratio
38
+ * `numer(x)/denom(x)` is unchanged).
39
+ *
40
+ * Returns `null` when `expr` is not a rational function of `v`: it contains
41
+ * a transcendental call (`sin`/`exp`/... — any identifier other than `v`),
42
+ * more than one variable, a zero denominator, or coefficients that cannot be
43
+ * cleared to integers.
44
+ */
45
+ export declare function parseRationalFunction(expr: string, v: string): RatFunc | null;
46
+ /**
47
+ * Exact-ℚ polynomial long division of `rf.numer` by `rf.denom`:
48
+ * `numer = quotient·denom + remainder`, `deg(remainder) < deg(denom)`.
49
+ * Division is performed over ℚ (so a non-monic denominator is handled
50
+ * correctly); the result is converted back to `bigint` coefficients, which
51
+ * requires every intermediate `Rat` to reduce to an integer denominator —
52
+ * true whenever the division is itself exact-integer, as it is for a
53
+ * genuine rational-function reduction. Throws if it is not (a caller that
54
+ * expects a non-integer quotient/remainder is out of this module's scope).
55
+ */
56
+ export declare function polynomialPart(rf: RatFunc): {
57
+ quotient: IntPoly;
58
+ remainder: IntPoly;
59
+ };
60
+ /**
61
+ * Termwise power rule: the coefficient `c` at degree `n` in `p` integrates
62
+ * to `c/(n+1) · v^(n+1)`. Renders a readable (not contractual beyond
63
+ * containing the expected power) string, e.g. `x^2/2`, `2*x`.
64
+ */
65
+ export declare function integratePolynomial(p: IntPoly, v: string): string;
66
+ /**
67
+ * An irreducible factor of a rational function's denominator, classified by
68
+ * degree for Layer 1 closed-form integration: degree 1 ("linear") integrates
69
+ * to a `log`, degree 2 ("quadratic") to a `log` + `atan` pair. Degree ≥ 3
70
+ * irreducible factors are outside Layer 1's scope (see `factorDenominator`).
71
+ */
72
+ export interface DenFactor {
73
+ poly: IntPoly;
74
+ mult: number;
75
+ kind: 'linear' | 'quadratic';
76
+ }
77
+ /**
78
+ * Factors `denom` completely over ℤ/ℚ via the #7 factorization engine
79
+ * (`factorUnivariateZ`) and classifies each irreducible factor by degree.
80
+ *
81
+ * A degree-1 factor is `'linear'`; a degree-2 factor is `'quadratic'` — and,
82
+ * having survived complete factorization over ℚ, necessarily irreducible
83
+ * (any rational root would already have split it into two linear factors,
84
+ * i.e. it has negative discriminant).
85
+ *
86
+ * Returns `null` when any irreducible factor has degree ≥ 3: Layer 1 only
87
+ * handles linear + irreducible-quadratic denominators, so a higher-degree
88
+ * irreducible factor is out of scope and the caller falls back to the
89
+ * `integral(...)` marker (Layer 2/Rothstein–Trager territory).
90
+ */
91
+ export declare function factorDenominator(denom: IntPoly): DenFactor[] | null;
92
+ /**
93
+ * A single partial-fraction term `numer(x) / factor(x)^power`. `numer` is a
94
+ * `Rat[]` of fixed length `deg(factor)` (index = degree, ascending — the same
95
+ * convention as `IntPoly`): length 1 (a constant) over a linear factor,
96
+ * length 2 (`[E, D]` meaning `D*x + E`) over a quadratic factor.
97
+ */
98
+ export interface PFTerm {
99
+ factor: IntPoly;
100
+ power: number;
101
+ numer: Rat[];
102
+ }
103
+ /**
104
+ * Exact-ℚ partial-fraction decomposition of `remainder(x) / ∏ factorᵢ(x)^multᵢ`
105
+ * (`deg(remainder) < deg(∏ factorᵢ^multᵢ)`, as produced by `polynomialPart`)
106
+ * into the standard form: for each irreducible factor `qᵢ` with multiplicity
107
+ * `mᵢ`, terms `A_{i,k}(x) / qᵢ(x)^k` for `k = 1..mᵢ`, `deg A_{i,k} < deg qᵢ`.
108
+ *
109
+ * Solved by clearing denominators: multiplying the ansatz by the full
110
+ * denominator `D = ∏ factorⱼ^multⱼ` turns each unknown numerator coefficient
111
+ * into a linear unknown whose column is the polynomial
112
+ * `x^j · qᵢ(x)^{mᵢ−k} · ∏_{j≠i} factorⱼ(x)^multⱼ` (a plain integer polynomial
113
+ * product — no division is ever needed, since `mᵢ−k ≥ 0`). Equating
114
+ * coefficients of `remainder(x)` on both sides gives a square (`deg D` ×
115
+ * `deg D`) rational linear system, solved exactly via `solveLinearSystemRat`.
116
+ */
117
+ export declare function partialFractions(remainder: IntPoly, factors: DenFactor[]): PFTerm[];
118
+ /**
119
+ * Integrates a single partial-fraction term in closed form. Dispatches on the
120
+ * degree of `term.factor`: degree 1 → `log` (+ rational part for a repeated
121
+ * factor); degree 2 (irreducible, disc < 0) → `log`/rational part + `atan`.
122
+ * The produced string is evaluable by the expression engine (`log`, `atan`,
123
+ * `sqrt`, `abs`, `^`, `*`); its exact form is not contractual — correctness is
124
+ * verified by differentiation. Throws on any other factor degree (unreachable
125
+ * for a `factorDenominator`-classified factor).
126
+ */
127
+ export declare function integratePFTerm(term: PFTerm, v: string): string;
128
+ /**
129
+ * Full Layer-1 rational-function integration pipeline. Parses `expr` into an
130
+ * exact integer rational function, splits off and integrates the polynomial
131
+ * part, factors the denominator into linear + irreducible-quadratic factors,
132
+ * decomposes into exact-ℚ partial fractions, and integrates each term in
133
+ * closed form (rational part + `log` + `atan`).
134
+ *
135
+ * Returns `null` when `expr` is not a rational function of `v`
136
+ * (`parseRationalFunction` declines), when the denominator has a degree-≥3
137
+ * irreducible factor (`factorDenominator` declines — Layer 2 territory), or
138
+ * when any internal step throws (e.g. a non-integer polynomial-part division),
139
+ * so callers get a clean decline rather than an exception.
140
+ */
141
+ export declare function integrateRationalFunction(expr: string, v: string): string | null;
142
+ //# sourceMappingURL=rational-integrate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rational-integrate.d.ts","sourceRoot":"","sources":["../../src/cas/rational-integrate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAGH,OAAO,EAKL,KAAK,OAAO,EACb,MAAM,wCAAwC,CAAC;AAGhD,4FAA4F;AAC5F,MAAM,WAAW,GAAG;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,GAAG,EAAE,MAAM,CAAC;CACb;AAED,2FAA2F;AAC3F,MAAM,WAAW,OAAO;IACtB,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,EAAE,OAAO,CAAC;CAChB;AAoBD,wBAAgB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,GAAG,GAAG,CAE1C;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,GAAG,GAAG,CAE1C;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,GAAG,GAAG,CAE1C;AAED,wBAAgB,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,GAAG,GAAG,GAAG,CAK1C;AAED,wBAAgB,aAAa,CAAC,CAAC,EAAE,MAAM,GAAG,GAAG,CAE5C;AAsDD;;;;;;;;;;;;GAYG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,GAAG,IAAI,CA4C7E;AAWD;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,EAAE,EAAE,OAAO,GAAG;IAAE,QAAQ,EAAE,OAAO,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAoCrF;AAWD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,CAAC,EAAE,OAAO,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAiBjE;AAED;;;;;GAKG;AACH,MAAM,WAAW,SAAS;IACxB,IAAI,EAAE,OAAO,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,QAAQ,GAAG,WAAW,CAAC;CAC9B;AAED;;;;;;;;;;;;;GAaG;AACH,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,GAAG,SAAS,EAAE,GAAG,IAAI,CA0BpE;AAED;;;;;GAKG;AACH,MAAM,WAAW,MAAM;IACrB,MAAM,EAAE,OAAO,CAAC;IAChB,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,GAAG,EAAE,CAAC;CACd;AA0DD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,SAAS,EAAE,OAAO,EAAE,OAAO,EAAE,SAAS,EAAE,GAAG,MAAM,EAAE,CA4EnF;AAkLD;;;;;;;;GAQG;AACH,wBAAgB,eAAe,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,CAU/D;AAED;;;;;;;;;;;;GAYG;AACH,wBAAgB,yBAAyB,CAAC,IAAI,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CA+ChF"}
@@ -4,12 +4,17 @@
4
4
  * integrand is outside the supported subset, returns `integral(expr, variable)`.
5
5
  *
6
6
  * The direct recursion is tried first; on failure, partial-fraction integration
7
- * (for rational integrands) and tabular integration by parts (for
8
- * polynomial·{exp,sin,cos}) are attempted before giving up with the marker.
7
+ * (for distinct-rational-root integrands), tabular integration by parts (for
8
+ * polynomial·{exp,sin,cos}), and full rational-function integration (Risch
9
+ * Layer 1) are attempted before giving up with the marker. Rational functions
10
+ * with irreducible-quadratic and repeated factors are now integrated (rational
11
+ * part + `log` + `arctan`); degree-≥3 irreducible denominators and transcendental
12
+ * Risch remain out of scope (marker).
9
13
  *
10
14
  * @example symbolicIntegral('x^3') // 'x^4 / 4'
11
15
  * @example symbolicIntegral('cos(3*x + 1)') // 'sin(3 * x + 1) / 3'
12
16
  * @example symbolicIntegral('1/(x^2 - 1)') // partial fractions → sum of logs
17
+ * @example symbolicIntegral('1/(x^2 + 1)') // Risch Layer 1 → 'atan(...)'
13
18
  * @example symbolicIntegral('x * sin(x)') // by parts → 'sin(x) - x*cos(x)'
14
19
  */
15
20
  export declare function symbolicIntegral(expr: string, variable?: string): string;
@@ -1 +1 @@
1
- {"version":3,"file":"cas-integration.d.ts","sourceRoot":"","sources":["../src/cas-integration.ts"],"names":[],"mappings":"AAoWA;;;;;;;;;;;;;GAaG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAM,GAAG,MAAM,CAWrE"}
1
+ {"version":3,"file":"cas-integration.d.ts","sourceRoot":"","sources":["../src/cas-integration.ts"],"names":[],"mappings":"AA2WA;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,MAAM,EAAE,QAAQ,SAAM,GAAG,MAAM,CAYrE"}
package/dist/index.js CHANGED
@@ -50609,6 +50609,468 @@ function lsqBounded(A, b, lower, upper, opts = {}) {
50609
50609
  return { x, residual: residualNorm(A, x, b) };
50610
50610
  }
50611
50611
 
50612
+ // src/cas/rational-integrate.ts
50613
+ function ratNormalize(num2, den) {
50614
+ if (den === 0n) {
50615
+ throw new Error("Rat: zero denominator");
50616
+ }
50617
+ let n = num2;
50618
+ let d = den;
50619
+ if (d < 0n) {
50620
+ n = -n;
50621
+ d = -d;
50622
+ }
50623
+ if (n === 0n) {
50624
+ return { num: 0n, den: 1n };
50625
+ }
50626
+ const g = bigintGcd(n, d);
50627
+ return { num: n / g, den: d / g };
50628
+ }
50629
+ function ratSub(a, b) {
50630
+ return ratNormalize(a.num * b.den - b.num * a.den, a.den * b.den);
50631
+ }
50632
+ function ratMul(a, b) {
50633
+ return ratNormalize(a.num * b.num, a.den * b.den);
50634
+ }
50635
+ function ratDiv(a, b) {
50636
+ if (b.num === 0n) {
50637
+ throw new Error("Rat: division by zero");
50638
+ }
50639
+ return ratNormalize(a.num * b.den, a.den * b.num);
50640
+ }
50641
+ function ratFromBigint(n) {
50642
+ return { num: n, den: 1n };
50643
+ }
50644
+ var RAT_ZERO = { num: 0n, den: 1n };
50645
+ function splitTopLevelDivision(expr) {
50646
+ let depth = 0;
50647
+ for (let i = 0; i < expr.length; i += 1) {
50648
+ const c = expr[i];
50649
+ if (c === "(") {
50650
+ depth += 1;
50651
+ } else if (c === ")") {
50652
+ depth -= 1;
50653
+ } else if (c === "/" && depth === 0) {
50654
+ return { numerStr: expr.slice(0, i), denomStr: expr.slice(i + 1) };
50655
+ }
50656
+ }
50657
+ return { numerStr: expr, denomStr: "1" };
50658
+ }
50659
+ function denseFromPoly(p) {
50660
+ let maxPow = 0;
50661
+ for (const t of p) {
50662
+ maxPow = Math.max(maxPow, t.powers[0] ?? 0);
50663
+ }
50664
+ const dense = new Array(maxPow + 1).fill(0);
50665
+ for (const t of p) {
50666
+ dense[t.powers[0]] += t.coeff;
50667
+ }
50668
+ return dense;
50669
+ }
50670
+ var INT_EPS = 1e-7;
50671
+ function isCloseToInteger(x) {
50672
+ return Math.abs(x - Math.round(x)) < INT_EPS;
50673
+ }
50674
+ function commonDenominator(coeffs) {
50675
+ const LIMIT = 1e5;
50676
+ for (let k = 1; k <= LIMIT; k += 1) {
50677
+ if (coeffs.every((c) => isCloseToInteger(c * k))) {
50678
+ return k;
50679
+ }
50680
+ }
50681
+ return null;
50682
+ }
50683
+ function parseRationalFunction(expr, v) {
50684
+ const { numerStr, denomStr } = splitTopLevelDivision(expr);
50685
+ let numerPoly;
50686
+ let denomPoly;
50687
+ try {
50688
+ numerPoly = polyFromExpression(numerStr, [v]);
50689
+ denomPoly = polyFromExpression(denomStr, [v]);
50690
+ } catch {
50691
+ return null;
50692
+ }
50693
+ const numerDense = denseFromPoly(numerPoly);
50694
+ const denomDense = denseFromPoly(denomPoly);
50695
+ if (denomDense.every((c) => c === 0)) {
50696
+ return null;
50697
+ }
50698
+ const kNumer = commonDenominator(numerDense);
50699
+ const kDenom = commonDenominator(denomDense);
50700
+ if (kNumer === null || kDenom === null) {
50701
+ return null;
50702
+ }
50703
+ const scale4 = kNumer * kDenom;
50704
+ const toIntPoly = (dense) => {
50705
+ const out = new Array(dense.length);
50706
+ for (let i = 0; i < dense.length; i += 1) {
50707
+ const scaled = dense[i] * scale4;
50708
+ if (!isCloseToInteger(scaled)) {
50709
+ return null;
50710
+ }
50711
+ out[i] = BigInt(Math.round(scaled));
50712
+ }
50713
+ return trim(out);
50714
+ };
50715
+ const numer = toIntPoly(numerDense);
50716
+ const denom = toIntPoly(denomDense);
50717
+ if (numer === null || denom === null || denom.length === 0) {
50718
+ return null;
50719
+ }
50720
+ return { numer, denom };
50721
+ }
50722
+ function trimRat(p) {
50723
+ let n = p.length;
50724
+ while (n > 0 && p[n - 1].num === 0n) {
50725
+ n -= 1;
50726
+ }
50727
+ return p.slice(0, n);
50728
+ }
50729
+ function polynomialPart(rf) {
50730
+ const denom = trim(rf.denom);
50731
+ if (denom.length === 0) {
50732
+ throw new Error("polynomialPart: zero denominator");
50733
+ }
50734
+ const db = denom.length - 1;
50735
+ const lb = ratFromBigint(denom[db]);
50736
+ const denomRat = denom.map(ratFromBigint);
50737
+ let rem = trimRat(trim(rf.numer).map(ratFromBigint));
50738
+ const dq = rem.length - 1 - db;
50739
+ const quotient = new Array(Math.max(dq + 1, 0)).fill(RAT_ZERO);
50740
+ while (rem.length > 0 && rem.length - 1 >= db) {
50741
+ const dr = rem.length - 1;
50742
+ const shift = dr - db;
50743
+ const coeff = ratDiv(rem[dr], lb);
50744
+ quotient[shift] = coeff;
50745
+ const next = rem.slice();
50746
+ for (let i = 0; i <= db; i += 1) {
50747
+ next[shift + i] = ratSub(next[shift + i], ratMul(coeff, denomRat[i]));
50748
+ }
50749
+ rem = trimRat(next);
50750
+ }
50751
+ const toExactIntPoly = (rs) => trim(
50752
+ rs.map((r) => {
50753
+ if (r.den !== 1n) {
50754
+ throw new Error("polynomialPart: division introduced a non-integer coefficient");
50755
+ }
50756
+ return r.num;
50757
+ })
50758
+ );
50759
+ return { quotient: toExactIntPoly(quotient), remainder: toExactIntPoly(rem) };
50760
+ }
50761
+ function formatRatTerm(r, varPart) {
50762
+ const sign3 = r.num < 0n ? "-" : "";
50763
+ const absNum = r.num < 0n ? -r.num : r.num;
50764
+ const coeffPart = absNum === 1n ? "" : `${absNum}*`;
50765
+ const denPart = r.den === 1n ? "" : `/${r.den}`;
50766
+ return `${sign3}${coeffPart}${varPart}${denPart}`;
50767
+ }
50768
+ function integratePolynomial(p, v) {
50769
+ const trimmed = trim(p);
50770
+ const terms = [];
50771
+ for (let i = 0; i < trimmed.length; i += 1) {
50772
+ const c = trimmed[i];
50773
+ if (c === 0n) {
50774
+ continue;
50775
+ }
50776
+ const n = i + 1;
50777
+ const coeff = ratNormalize(c, BigInt(n));
50778
+ const varPart = n === 1 ? v : `${v}^${n}`;
50779
+ terms.push(formatRatTerm(coeff, varPart));
50780
+ }
50781
+ if (terms.length === 0) {
50782
+ return "0";
50783
+ }
50784
+ return terms.join(" + ").replace(/\+ -/g, "- ");
50785
+ }
50786
+ function factorDenominator(denom) {
50787
+ const { factors } = factorUnivariateZ(trim(denom));
50788
+ const out = [];
50789
+ for (const { poly, mult } of factors) {
50790
+ const deg = trim(poly).length - 1;
50791
+ if (deg === 1) {
50792
+ out.push({ poly, mult, kind: "linear" });
50793
+ } else if (deg === 2) {
50794
+ const q = trim(poly);
50795
+ const disc = q[1] * q[1] - 4n * q[2] * q[0];
50796
+ if (disc >= 0n) {
50797
+ return null;
50798
+ }
50799
+ out.push({ poly, mult, kind: "quadratic" });
50800
+ } else {
50801
+ return null;
50802
+ }
50803
+ }
50804
+ return out;
50805
+ }
50806
+ function shiftedColumn(poly, shift, size2) {
50807
+ const col = new Array(size2).fill(RAT_ZERO);
50808
+ for (let i = 0; i < poly.length; i += 1) {
50809
+ const row2 = i + shift;
50810
+ if (row2 < size2) {
50811
+ col[row2] = ratFromBigint(poly[i]);
50812
+ }
50813
+ }
50814
+ return col;
50815
+ }
50816
+ function solveLinearSystemRat(matrix2, rhs) {
50817
+ const n = rhs.length;
50818
+ const rows = matrix2.map((row2, r) => [...row2, rhs[r]]);
50819
+ for (let col = 0; col < n; col += 1) {
50820
+ let pivotRow = -1;
50821
+ for (let r = col; r < n; r += 1) {
50822
+ if (rows[r][col].num !== 0n) {
50823
+ pivotRow = r;
50824
+ break;
50825
+ }
50826
+ }
50827
+ if (pivotRow === -1) {
50828
+ throw new Error("partialFractions: singular partial-fraction linear system");
50829
+ }
50830
+ if (pivotRow !== col) {
50831
+ const tmp = rows[col];
50832
+ rows[col] = rows[pivotRow];
50833
+ rows[pivotRow] = tmp;
50834
+ }
50835
+ const pivotVal = rows[col][col];
50836
+ rows[col] = rows[col].map((v) => ratDiv(v, pivotVal));
50837
+ for (let r = 0; r < n; r += 1) {
50838
+ if (r === col) {
50839
+ continue;
50840
+ }
50841
+ const factor2 = rows[r][col];
50842
+ if (factor2.num === 0n) {
50843
+ continue;
50844
+ }
50845
+ const pivotRowVals = rows[col];
50846
+ rows[r] = rows[r].map((v, c) => ratSub(v, ratMul(factor2, pivotRowVals[c])));
50847
+ }
50848
+ }
50849
+ return rows.map((row2) => row2[n]);
50850
+ }
50851
+ function partialFractions(remainder, factors) {
50852
+ const trimmedRemainder = trim(remainder);
50853
+ const factorPowers = factors.map((f) => {
50854
+ const powers = [[1n]];
50855
+ let acc = [1n];
50856
+ for (let p = 1; p <= f.mult; p += 1) {
50857
+ acc = mul(acc, f.poly);
50858
+ powers.push(acc);
50859
+ }
50860
+ return powers;
50861
+ });
50862
+ const othersProduct = factors.map((_f, fi) => {
50863
+ let acc = [1n];
50864
+ for (let fj = 0; fj < factors.length; fj += 1) {
50865
+ if (fj === fi) {
50866
+ continue;
50867
+ }
50868
+ acc = mul(acc, factorPowers[fj][factors[fj].mult]);
50869
+ }
50870
+ return acc;
50871
+ });
50872
+ const degOf = (fi) => trim(factors[fi].poly).length - 1;
50873
+ const unknowns = [];
50874
+ for (let fi = 0; fi < factors.length; fi += 1) {
50875
+ const di = degOf(fi);
50876
+ for (let k = 1; k <= factors[fi].mult; k += 1) {
50877
+ for (let j = 0; j < di; j += 1) {
50878
+ unknowns.push({ fi, k, j });
50879
+ }
50880
+ }
50881
+ }
50882
+ const n = unknowns.length;
50883
+ const columns = unknowns.map(({ fi, k, j }) => {
50884
+ const remainingPower = factors[fi].mult - k;
50885
+ const coPoly = mul(othersProduct[fi], factorPowers[fi][remainingPower]);
50886
+ return shiftedColumn(coPoly, j, n);
50887
+ });
50888
+ const rows = [];
50889
+ for (let r = 0; r < n; r += 1) {
50890
+ rows.push(columns.map((col) => col[r]));
50891
+ }
50892
+ const rhs = new Array(n).fill(RAT_ZERO).map((_, idx2) => ratFromBigint(idx2 < trimmedRemainder.length ? trimmedRemainder[idx2] : 0n));
50893
+ const solution = n === 0 ? [] : solveLinearSystemRat(rows, rhs);
50894
+ const terms = [];
50895
+ let idx = 0;
50896
+ for (let fi = 0; fi < factors.length; fi += 1) {
50897
+ const di = degOf(fi);
50898
+ for (let k = 1; k <= factors[fi].mult; k += 1) {
50899
+ const numer = [];
50900
+ for (let j = 0; j < di; j += 1) {
50901
+ numer.push(solution[idx]);
50902
+ idx += 1;
50903
+ }
50904
+ terms.push({ factor: factors[fi].poly, power: k, numer });
50905
+ }
50906
+ }
50907
+ return terms;
50908
+ }
50909
+ function ratNeg(r) {
50910
+ return { num: -r.num, den: r.den };
50911
+ }
50912
+ function ratToStr(r) {
50913
+ return r.den === 1n ? `${r.num}` : `${r.num}/${r.den}`;
50914
+ }
50915
+ function renderCoeffTimes(r, rest) {
50916
+ const neg2 = r.num < 0n;
50917
+ const absNum = neg2 ? -r.num : r.num;
50918
+ const sign3 = neg2 ? "-" : "";
50919
+ if (absNum === r.den) {
50920
+ return `${sign3}${rest}`;
50921
+ }
50922
+ const denPart = r.den === 1n ? "" : `/${r.den}`;
50923
+ return `${sign3}${absNum}${denPart}*${rest}`;
50924
+ }
50925
+ function renderXMinus(a, v) {
50926
+ if (a.num === 0n) {
50927
+ return v;
50928
+ }
50929
+ if (a.num > 0n) {
50930
+ return `${v} - ${ratToStr(a)}`;
50931
+ }
50932
+ return `${v} + ${ratToStr(ratNeg(a))}`;
50933
+ }
50934
+ function renderQuadraticCore(b, c, v) {
50935
+ let s = `${v}^2`;
50936
+ if (b.num !== 0n) {
50937
+ s += ` + (${ratToStr(b)})*${v}`;
50938
+ }
50939
+ s += ` + (${ratToStr(c)})`;
50940
+ return s;
50941
+ }
50942
+ function renderTwoXPlusB(b, v) {
50943
+ let s = `2*${v}`;
50944
+ if (b.num !== 0n) {
50945
+ s += ` + (${ratToStr(b)})`;
50946
+ }
50947
+ return s;
50948
+ }
50949
+ function joinTerms(parts) {
50950
+ if (parts.length === 0) {
50951
+ return "0";
50952
+ }
50953
+ return parts.join(" + ").replace(/\+ -/g, "- ");
50954
+ }
50955
+ function integrateLinearTerm(factor2, k, numer, v) {
50956
+ const p0 = factor2[0];
50957
+ const p1 = factor2[1];
50958
+ const a = ratNeg(ratDiv(ratFromBigint(p0), ratFromBigint(p1)));
50959
+ const A = ratDiv(numer[0], ratFromBigint(p1 ** BigInt(k)));
50960
+ if (A.num === 0n) {
50961
+ return "0";
50962
+ }
50963
+ const xMinus = renderXMinus(a, v);
50964
+ if (k === 1) {
50965
+ return renderCoeffTimes(A, `log(abs(${xMinus}))`);
50966
+ }
50967
+ const coeff = ratNeg(ratDiv(A, ratFromBigint(BigInt(k - 1))));
50968
+ return renderCoeffTimes(coeff, `(${xMinus})^(${-(k - 1)})`);
50969
+ }
50970
+ function integrateInverseQuadraticPower(k, b, c) {
50971
+ if (k === 1) {
50972
+ return { terms: [], atanCoeff: ratFromBigint(1n) };
50973
+ }
50974
+ const prev = integrateInverseQuadraticPower(k - 1, b, c);
50975
+ const d2 = ratSub(ratMul(ratFromBigint(4n), c), ratMul(b, b));
50976
+ const denomFactor = ratMul(ratFromBigint(BigInt(k - 1)), d2);
50977
+ const newTermCoeff = ratDiv(ratFromBigint(1n), denomFactor);
50978
+ const propagate = ratDiv(ratFromBigint(BigInt(2 * (2 * k - 3))), denomFactor);
50979
+ const terms = prev.terms.map((t) => ({ coeff: ratMul(t.coeff, propagate), power: t.power }));
50980
+ terms.push({ coeff: newTermCoeff, power: k - 1 });
50981
+ return { terms, atanCoeff: ratMul(prev.atanCoeff, propagate) };
50982
+ }
50983
+ function integrateQuadraticTerm(factor2, k, numer, v) {
50984
+ const q0 = factor2[0];
50985
+ const q1 = factor2[1];
50986
+ const q2 = factor2[2];
50987
+ const b = ratDiv(ratFromBigint(q1), ratFromBigint(q2));
50988
+ const c = ratDiv(ratFromBigint(q0), ratFromBigint(q2));
50989
+ const leadPow = ratFromBigint(q2 ** BigInt(k));
50990
+ const D = ratDiv(numer[1], leadPow);
50991
+ const E = ratDiv(numer[0], leadPow);
50992
+ const d2 = ratSub(ratMul(ratFromBigint(4n), c), ratMul(b, b));
50993
+ const K = ratSub(E, ratMul(D, ratDiv(b, ratFromBigint(2n))));
50994
+ const qCore = renderQuadraticCore(b, c, v);
50995
+ const twoXb = renderTwoXPlusB(b, v);
50996
+ const parts = [];
50997
+ if (D.num !== 0n) {
50998
+ const half = ratDiv(D, ratFromBigint(2n));
50999
+ if (k === 1) {
51000
+ parts.push(renderCoeffTimes(half, `log(${qCore})`));
51001
+ } else {
51002
+ const coeff = ratNeg(ratDiv(half, ratFromBigint(BigInt(k - 1))));
51003
+ parts.push(renderCoeffTimes(coeff, `(${qCore})^(${-(k - 1)})`));
51004
+ }
51005
+ }
51006
+ if (K.num !== 0n) {
51007
+ const ik = integrateInverseQuadraticPower(k, b, c);
51008
+ for (const t of ik.terms) {
51009
+ const coeff = ratMul(K, t.coeff);
51010
+ if (coeff.num === 0n) {
51011
+ continue;
51012
+ }
51013
+ parts.push(renderCoeffTimes(coeff, `(${twoXb})/(${qCore})^(${t.power})`));
51014
+ }
51015
+ const atanCoeff = ratMul(ratMul(K, ik.atanCoeff), ratFromBigint(2n));
51016
+ if (atanCoeff.num !== 0n) {
51017
+ const d2s = ratToStr(d2);
51018
+ parts.push(renderCoeffTimes(atanCoeff, `atan((${twoXb})/sqrt(${d2s}))/sqrt(${d2s})`));
51019
+ }
51020
+ }
51021
+ return joinTerms(parts);
51022
+ }
51023
+ function integratePFTerm(term, v) {
51024
+ const factor2 = trim(term.factor);
51025
+ const deg = factor2.length - 1;
51026
+ if (deg === 1) {
51027
+ return integrateLinearTerm(factor2, term.power, term.numer, v);
51028
+ }
51029
+ if (deg === 2) {
51030
+ return integrateQuadraticTerm(factor2, term.power, term.numer, v);
51031
+ }
51032
+ throw new Error(`integratePFTerm: unsupported factor degree ${deg}`);
51033
+ }
51034
+ function integrateRationalFunction(expr, v) {
51035
+ try {
51036
+ const rf = parseRationalFunction(expr, v);
51037
+ if (rf === null) {
51038
+ return null;
51039
+ }
51040
+ const factors = factorDenominator(rf.denom);
51041
+ if (factors === null) {
51042
+ return null;
51043
+ }
51044
+ const { quotient, remainder } = polynomialPart(rf);
51045
+ const terms = partialFractions(remainder, factors);
51046
+ let prod2 = [1n];
51047
+ for (const { poly, mult } of factors) {
51048
+ for (let k = 0; k < mult; k += 1) prod2 = mul(prod2, poly);
51049
+ }
51050
+ const scalePoly = exactDivide(rf.denom, prod2);
51051
+ if (scalePoly !== null && scalePoly.length === 1 && scalePoly[0] !== 1n) {
51052
+ const scale4 = ratFromBigint(scalePoly[0]);
51053
+ for (const term of terms) {
51054
+ term.numer = term.numer.map((c) => ratDiv(c, scale4));
51055
+ }
51056
+ }
51057
+ const parts = [];
51058
+ const polyPart = integratePolynomial(quotient, v);
51059
+ if (polyPart !== "0") {
51060
+ parts.push(polyPart);
51061
+ }
51062
+ for (const term of terms) {
51063
+ const s = integratePFTerm(term, v);
51064
+ if (s !== "0") {
51065
+ parts.push(s);
51066
+ }
51067
+ }
51068
+ return joinTerms(parts);
51069
+ } catch {
51070
+ return null;
51071
+ }
51072
+ }
51073
+
50612
51074
  // src/cas-integration.ts
50613
51075
  var parse2 = parse;
50614
51076
  var evaluate2 = evaluate;
@@ -50846,7 +51308,7 @@ function symbolicIntegral(expr, variable = "x") {
50846
51308
  return integrateNode(parse2(expr), variable);
50847
51309
  } catch (e) {
50848
51310
  if (!(e instanceof NotIntegrable)) throw e;
50849
- return tryPartialFractions(expr, variable) ?? tryByParts(expr, variable) ?? `integral(${expr}, ${variable})`;
51311
+ return tryPartialFractions(expr, variable) ?? tryByParts(expr, variable) ?? integrateRationalFunction(expr, variable) ?? `integral(${expr}, ${variable})`;
50850
51312
  }
50851
51313
  }
50852
51314
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@danielsimonjr/mathts-functions",
3
- "version": "0.59.0",
3
+ "version": "0.60.0",
4
4
  "description": "Mathematical functions for MathTS - arithmetic, algebra, trigonometry, statistics, and more",
5
5
  "author": "Daniel Simon Jr.",
6
6
  "license": "MIT",