|
| 1 | +// |
| 2 | +// Copyright (c) 2019-2026 Angouri. |
| 3 | +// AngouriMath is licensed under MIT. |
| 4 | +// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md. |
| 5 | +// Website: https://am.angouri.org. |
| 6 | +// |
| 7 | + |
| 8 | +using PeterO.Numbers; |
| 9 | +using static AngouriMath.Entity; |
| 10 | +using static AngouriMath.Entity.Number; |
| 11 | + |
| 12 | +namespace AngouriMath.Functions |
| 13 | +{ |
| 14 | + /// <summary> |
| 15 | + /// A summation whose summand is a polynomial in the index, written as a polynomial in the |
| 16 | + /// bounds: <c>sum(k, k, 1, n)</c> is <c>n^2/2 + n/2</c>. |
| 17 | + /// </summary> |
| 18 | + /// <remarks> |
| 19 | + /// <para> |
| 20 | + /// The operator writes itself out term by term where the bounds are concrete and few, and |
| 21 | + /// otherwise stayed as written — so a symbolic bound had no answer at all, and neither did a |
| 22 | + /// concrete range past a hundred terms. Both are the same gap: a sum of a polynomial has a |
| 23 | + /// closed form, and computing it is cheaper than the expansion it replaces. |
| 24 | + /// </para> |
| 25 | + /// <para> |
| 26 | + /// <b>No Bernoulli numbers.</b> The sum of a degree-<c>d</c> polynomial in the index is a |
| 27 | + /// polynomial of degree <c>d + 1</c> in the bound, which is the whole of what is needed: a |
| 28 | + /// polynomial of that degree is determined by <c>d + 2</c> of its values, and those values |
| 29 | + /// are sums of <c>d + 2</c> terms each, computed directly. Interpolating them recovers the |
| 30 | + /// coefficients exactly, in rational arithmetic, with no table to carry and no identity to |
| 31 | + /// get subtly wrong. Faulhaber's formula would give the same answer by a shorter route that |
| 32 | + /// needs Bernoulli numbers, which the library does not have. |
| 33 | + /// </para> |
| 34 | + /// <para> |
| 35 | + /// <b>The condition is not decoration.</b> <c>sum(k, k, 1, n)</c> is <em>not</em> |
| 36 | + /// <c>n^2/2 + n/2</c> for every <c>n</c>: at <c>n = -2</c> the range is empty and this |
| 37 | + /// library answers an empty range with <c>0</c>, while the polynomial gives <c>1</c>. The |
| 38 | + /// identity holds exactly when <c>to >= from - 1</c>, so that is what is attached, with the |
| 39 | + /// empty-range value as the other branch. Where the bounds are concrete the condition is |
| 40 | + /// decidable and the piecewise collapses to a number. |
| 41 | + /// </para> |
| 42 | + /// <para> |
| 43 | + /// SymPy answers the same input with the bare polynomial and is not making a mistake: it |
| 44 | + /// reads a reversed range as the negated sum over the flipped one, under which the identity |
| 45 | + /// is unconditional. This library defines an empty range as the operator's identity instead, |
| 46 | + /// and the condition is what that choice costs. |
| 47 | + /// </para> |
| 48 | + /// </remarks> |
| 49 | + internal static class PolynomialSummation |
| 50 | + { |
| 51 | + /// <summary> |
| 52 | + /// The degree of summand this will take. The work is cubic in it and the coefficients |
| 53 | + /// carry factorials of it, so the ceiling is about the size of the answer rather than |
| 54 | + /// about the method, which has no upper bound of its own. |
| 55 | + /// </summary> |
| 56 | + private const int MaxDegree = 16; |
| 57 | + |
| 58 | + /// <summary> |
| 59 | + /// <c>sum(expression, index, from, to)</c> written in closed form, or |
| 60 | + /// <see langword="null"/> where the summand is not a polynomial in the index. |
| 61 | + /// </summary> |
| 62 | + internal static Entity? ClosedForm(Entity expression, Entity var, Entity from, Entity to) |
| 63 | + { |
| 64 | + if (var is not Variable index) |
| 65 | + return null; |
| 66 | + // A bound that is a number and not a whole one is not a bound this identity is about. |
| 67 | + // The index runs over the integers, so `sum(k, k, 1, 5/2)` is 1 + 2 = 3, while the |
| 68 | + // polynomial continued to 5/2 is 35/8 -- a different question, confidently answered. |
| 69 | + // `+oo` fails the same test, and so does every other non-integer number. |
| 70 | + if (!IsWholeOrSymbolic(from) || !IsWholeOrSymbolic(to)) |
| 71 | + return null; |
| 72 | + if (!TreeAnalyzer.TryGetPolynomial(expression, index, out var monomials)) |
| 73 | + return null; |
| 74 | + |
| 75 | + var degree = 0; |
| 76 | + foreach (var monomial in monomials) |
| 77 | + { |
| 78 | + if (monomial.Key.Sign < 0 || !monomial.Key.CanFitInInt32()) |
| 79 | + return null; |
| 80 | + var power = monomial.Key.ToInt32Checked(); |
| 81 | + if (power > MaxDegree) |
| 82 | + return null; |
| 83 | + // A coefficient that still mentions the index means the reading did not separate |
| 84 | + // them, and summing it as a constant would be answering a different question. |
| 85 | + if (monomial.Value.ContainsNode(index)) |
| 86 | + return null; |
| 87 | + if (power > degree) |
| 88 | + degree = power; |
| 89 | + } |
| 90 | + |
| 91 | + // S(m) = sum over k from 1 to m of the summand, as a polynomial in m. One power sum |
| 92 | + // per power present, weighted by that power's coefficient. |
| 93 | + Entity AtBound(Entity bound) |
| 94 | + { |
| 95 | + Entity total = Integer.Create(0); |
| 96 | + foreach (var monomial in monomials) |
| 97 | + total += monomial.Value * Evaluate(PowerSum(monomial.Key.ToInt32Checked()), bound); |
| 98 | + return total; |
| 99 | + } |
| 100 | + |
| 101 | + // sum from a to b is S(b) - S(a - 1), which holds for every pair of integers with |
| 102 | + // b >= a - 1 -- at b = a - 1 both sides are zero, and below it the range is empty |
| 103 | + // while the polynomial is not. |
| 104 | + var closed = (AtBound(to) - AtBound(from - 1)).InnerSimplified; |
| 105 | + var nonEmpty = new GreaterOrEqualf(to, from - 1); |
| 106 | + return MathS.Piecewise(new[] |
| 107 | + { |
| 108 | + new Providedf(closed, nonEmpty), |
| 109 | + new Providedf(Integer.Create(0), Entity.Boolean.True), |
| 110 | + }).InnerSimplified; |
| 111 | + } |
| 112 | + |
| 113 | + /// <summary> |
| 114 | + /// Whether a bound is one this identity can speak about: a whole number, or a name, of |
| 115 | + /// which the second is read as standing for a whole number because that is what the |
| 116 | + /// index of a summation ranges over. |
| 117 | + /// </summary> |
| 118 | + /// <remarks> |
| 119 | + /// Only a bound that <em>evaluates to a number</em> and is not whole is refused. That |
| 120 | + /// covers <c>5/2</c>, <c>+oo</c> and <c>1.5</c>, and leaves both a literal integer and |
| 121 | + /// anything symbolic to go through — the symbolic case being the one the closed form |
| 122 | + /// exists for. |
| 123 | + /// </remarks> |
| 124 | + private static bool IsWholeOrSymbolic(Entity bound) |
| 125 | + => bound.Evaled is Integer || bound.Evaled is not Number; |
| 126 | + |
| 127 | + /// <summary> |
| 128 | + /// The coefficients of <c>sum of k^power for k from 1 to m</c> as a polynomial in |
| 129 | + /// <c>m</c>, lowest power first. |
| 130 | + /// </summary> |
| 131 | + /// <remarks> |
| 132 | + /// A polynomial of degree <c>power + 1</c>, so <c>power + 2</c> of its values determine |
| 133 | + /// it. They are taken at <c>m = 0, 1, ..., power + 1</c>, where each is a sum of at most |
| 134 | + /// <c>power + 1</c> whole numbers, and Lagrange's formula turns them back into |
| 135 | + /// coefficients. |
| 136 | + /// </remarks> |
| 137 | + private static ERational[] PowerSum(int power) |
| 138 | + { |
| 139 | + var points = power + 2; |
| 140 | + var values = new ERational[points]; |
| 141 | + var running = EInteger.Zero; |
| 142 | + for (var m = 0; m < points; m++) |
| 143 | + { |
| 144 | + if (m > 0) |
| 145 | + running = running.Add(EInteger.FromInt32(m).Pow(power)); |
| 146 | + values[m] = ERational.Create(running, EInteger.One); |
| 147 | + } |
| 148 | + return Interpolate(values); |
| 149 | + } |
| 150 | + |
| 151 | + /// <summary> |
| 152 | + /// The polynomial through <c>(i, values[i])</c> for each <c>i</c>, by Lagrange's formula, |
| 153 | + /// as coefficients lowest power first. |
| 154 | + /// </summary> |
| 155 | + private static ERational[] Interpolate(ERational[] values) |
| 156 | + { |
| 157 | + var result = new ERational[values.Length]; |
| 158 | + for (var i = 0; i < result.Length; i++) |
| 159 | + result[i] = ERational.Zero; |
| 160 | + |
| 161 | + for (var i = 0; i < values.Length; i++) |
| 162 | + { |
| 163 | + // The basis polynomial for node i: the product of (x - j) over every other node, |
| 164 | + // divided by the same product evaluated at i. |
| 165 | + // Zeroed rather than left default: ERational is a class, so an unassigned entry |
| 166 | + // is null and the multiplication below reads every one of them. |
| 167 | + var basis = new ERational[values.Length]; |
| 168 | + for (var k = 0; k < basis.Length; k++) |
| 169 | + basis[k] = ERational.Zero; |
| 170 | + basis[0] = ERational.One; |
| 171 | + var filled = 1; |
| 172 | + var denominator = ERational.One; |
| 173 | + for (var j = 0; j < values.Length; j++) |
| 174 | + { |
| 175 | + if (j == i) |
| 176 | + continue; |
| 177 | + // Multiply by (x - j), in place and from the top down so that a coefficient |
| 178 | + // is read before it is overwritten. |
| 179 | + for (var k = filled; k > 0; k--) |
| 180 | + basis[k] = basis[k - 1].Subtract(basis[k].Multiply(ERational.FromInt32(j))); |
| 181 | + basis[0] = basis[0].Multiply(ERational.FromInt32(-j)); |
| 182 | + filled++; |
| 183 | + denominator = denominator.Multiply(ERational.FromInt32(i - j)); |
| 184 | + } |
| 185 | + |
| 186 | + var scale = values[i].Divide(denominator); |
| 187 | + for (var k = 0; k < result.Length; k++) |
| 188 | + result[k] = result[k].Add(basis[k].Multiply(scale)); |
| 189 | + } |
| 190 | + return result; |
| 191 | + } |
| 192 | + |
| 193 | + /// <summary> |
| 194 | + /// A rational-coefficient polynomial evaluated at <paramref name="at"/>, as a flat sum of |
| 195 | + /// terms rather than by Horner: the answer is read by a person, and |
| 196 | + /// <c>n / 2 + n ^ 2 / 2</c> is the form this sum is known by, where the nested one is the |
| 197 | + /// same number written as nobody writes it. |
| 198 | + /// </summary> |
| 199 | + private static Entity Evaluate(ERational[] coefficients, Entity at) |
| 200 | + { |
| 201 | + Entity total = Integer.Create(0); |
| 202 | + for (var power = 0; power < coefficients.Length; power++) |
| 203 | + { |
| 204 | + if (coefficients[power].IsZero) |
| 205 | + continue; |
| 206 | + var coefficient = Rational.Create(coefficients[power]); |
| 207 | + total += power switch |
| 208 | + { |
| 209 | + 0 => coefficient, |
| 210 | + 1 => coefficient * at, |
| 211 | + _ => coefficient * MathS.Pow(at, Integer.Create(power)), |
| 212 | + }; |
| 213 | + } |
| 214 | + return total; |
| 215 | + } |
| 216 | + } |
| 217 | +} |
0 commit comments