Skip to content

Commit a169363

Browse files
A polynomial summand is summed in closed form (#1152)
A summation wrote itself out term by term where the bounds were concrete and there were fewer than a hundred terms, and was carried otherwise. So a symbolic bound had no answer at all, and neither did a long concrete range. Both are the same gap: a sum of a polynomial has a closed form, and computing it is cheaper than the expansion it replaces. sum(k, k, 1, n) was carried is piecewise((n + n ^ 2) / 2 provided n >= 0, 0) sum(k, k, 1, 100000) was carried is 5000050000 Any polynomial summand follows by linearity, a coefficient free of the index is carried through, and a symbolic lower bound works too -- `sum(k, k, m, n)` being `S(n) - S(m - 1)` like any other. The condition is the point rather than a caveat. `sum(k, k, 1, n)` is not `(n + n^2)/2` for every `n`: at `n = -2` the range is empty, and this library answers an empty range with the operator's identity -- `sum(k, k, 5, 1)` is `0`, which has its own test -- while the polynomial there is `1`. The identity holds exactly where `to >= from - 1`, so that is attached, with the empty-range value as the other branch. Where the bounds are concrete the condition is decidable and the whole thing collapses to a number, which is why the long range comes back an integer. SymPy prints the bare polynomial for the same input and is not wrong: it reads a reversed range as the negated sum over the flipped one, under which no condition is needed. The condition is what this library's different convention costs. A bound that is a number and not a whole one is still carried. The index runs over the integers, so `sum(k, k, 1, 5/2)` is `1 + 2`, while the polynomial continued to `5/2` is `35/8` -- a different question, confidently answered. The full suite caught that before it shipped, through the test that holds Syntax.md to its word. `+oo` is refused the same way, so an infinite series is untouched. A product is unchanged whatever its body. `factorial(n)` would be a wrong answer for `product(k, k, 1, n)` rather than a missing one: the empty product is `1` at every `n < 1` and `factorial` is undefined at the negative integers. It wants the same kind of condition and is not done here. No Bernoulli numbers. The sum of a degree-d polynomial is a polynomial of degree d+1, so d+2 of its values determine it, and those values are short sums computed directly; interpolating them recovers the coefficients exactly in rational arithmetic. Faulhaber's formula is the shorter route and needs a table the library does not have. Syntax.md and MathS.Sum's summary say what happens now. Comparison.md's `declines` cell is deliberately left as measured -- that table records one harness run at one commit, and a hand-corrected cell would be a measurement nobody took -- with a dated note beside it. Full suite 9459 passed, 0 failed. Part of #717. Claude-Session: https://claude.ai/code/session_012sonx8iAspMiwRwokT1Ura Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
1 parent e3c6b76 commit a169363

10 files changed

Lines changed: 572 additions & 16 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,53 @@ read first.
107107
| **Silent** | `"arccotan(-1)".ToEntity().Simplify()`, and every negative argument the inverse-trigonometric table knows | `3/4 * pi` — the textbook range, and **not equal to `arccotan(-1)`**, whose value is `-pi/4` | `-1/4 * pi` |
108108
| | `"e ^ ln(x)".ToEntity().Simplify()`, and every exponential of a natural logarithm | `e ^ ln(x)` — left as written | `x` |
109109
| | `"a => a + 3".ToEntity()`, and every lambda written with an arrow | `UnhandledParseException` | `lambda(a, a + 3)` |
110+
| | `"sum(k, k, 1, n)".ToEntity().Simplify()`, and every summation whose body is a polynomial in the index | `sum(k, k, 1, n)` — carried | `piecewise((n + n ^ 2) / 2 provided n >= 0, 0)` |
111+
| | `"sum(k, k, 1, 100000)".ToEntity().Simplify()`, and every concrete range past a hundred terms | `sum(k, k, 1, 100000)` — carried | `5000050000` |
112+
113+
### A polynomial summand is summed in closed form
114+
115+
A summation wrote itself out term by term where the bounds were concrete and there were fewer
116+
than a hundred terms, and was carried otherwise. So a symbolic bound had no answer, and neither
117+
did a long concrete range — both now do, where the body is a polynomial in the index.
118+
119+
```
120+
"sum(k, k, 1, n)".Simplify() was sum(k, k, 1, n)
121+
is piecewise((n + n ^ 2) / 2 provided n >= 0, 0)
122+
123+
"sum(k, k, 1, 100000)".Simplify() was sum(k, k, 1, 100000)
124+
is 5000050000
125+
```
126+
127+
`sum(k^2, k, 1, n)` and `sum(k^3, k, 1, n)` come with it, as does any polynomial summand by
128+
linearity, a coefficient that does not mention the index — `sum(a*k^2 + b*k + c, k, 1, n)` — and a
129+
symbolic *lower* bound, `sum(k, k, m, n)` being `S(n) - S(m - 1)` like any other.
130+
131+
**The condition is the entry.** `sum(k, k, 1, n)` is **not** `(n + n^2)/2` for every `n`. At
132+
`n = -2` the range is empty, and this library answers an empty range with the operator's identity
133+
— `sum(k, k, 5, 1)` is `0`, which has its own test — while the polynomial there is `1`. The
134+
identity holds exactly where `to >= from - 1`, so that is what is attached, with the empty-range
135+
value as the other branch. Where the bounds are concrete the condition is decidable and the whole
136+
thing collapses to a number, which is why the long range above is an integer and not a piecewise.
137+
138+
SymPy prints the bare polynomial for the same input and is not making a mistake: it reads a
139+
reversed range as the negated sum over the flipped one, under which the identity needs no
140+
condition. The condition is what this library's different convention costs, and **code that
141+
expected a bare polynomial from `Simplify` gets a `Piecewise`.**
142+
143+
**A bound that is a number and not a whole one is still carried.** The index runs over the
144+
integers, so `sum(k, k, 1, 5/2)` is `1 + 2`; the polynomial continued to `5/2` is `35/8`, which
145+
answers a different question. `+oo` is refused the same way, so an infinite series is untouched.
146+
147+
**A product is unchanged, whatever its body.** `product(k, k, 1, n)` is still carried, and
148+
`factorial(n)` would be a wrong answer for it rather than a missing one: the empty product is `1`
149+
at every `n < 1`, and `factorial` is undefined at the negative integers. Answering it needs the
150+
same kind of condition the sum now carries, and is not done here.
151+
152+
No Bernoulli numbers are involved. The sum of a degree-`d` polynomial is a polynomial of degree
153+
`d + 1`, so `d + 2` of its values determine it, and those values are short sums computed directly;
154+
interpolating them recovers the coefficients exactly in rational arithmetic.
155+
156+
[#717](https://github.com/asc-community/AngouriMath/issues/717).
110157

111158
### A lambda is written with an arrow as well as a call
112159

‎Sources/.editorconfig‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,8 @@ file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed
176176

177177
[Tests/UnitTests/Calculus/ApplicationDerivativeTest.cs]
178178
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
179+
180+
[AngouriMath/Functions/Algebra/Polynomials/PolynomialSummation.cs]
181+
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n
182+
[Tests/UnitTests/Core/ClosedFormSummationTest.cs]
183+
file_header_template=\nCopyright (c) 2019-2026 Angouri.\nAngouriMath is licensed under MIT.\nDetails: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.\nWebsite: https://am.angouri.org.\n

‎Sources/AngouriMath/Convenience/MathS.cs‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6963,12 +6963,20 @@ public static Entity Limit(Entity expr, Entity var, Entity dest, ApproachFrom ap
69636963
/// <param name="to">The last value of the index, inclusive.</param>
69646964
/// <returns>
69656965
/// The sum written out where the bounds are concrete integers and there are not too many
6966-
/// terms, and an unevaluated <see cref="Entity.Summationf"/> otherwise — so a symbolic
6967-
/// bound is carried rather than refused.
6966+
/// terms; a closed form where the body is a polynomial in the index, whatever the bounds;
6967+
/// and an unevaluated <see cref="Entity.Summationf"/> otherwise — so a body this cannot
6968+
/// read is carried rather than refused.
69686969
/// </returns>
69696970
/// <remarks>
6971+
/// <para>
69706972
/// An empty range sums to <c>0</c>, which is stated rather than left to fall out of the
69716973
/// loop. <a href="https://github.com/asc-community/AngouriMath/issues/248">#248</a>
6974+
/// </para>
6975+
/// <para>
6976+
/// That convention is why a closed form carries a condition: <c>sum(k, k, 1, n)</c> is
6977+
/// <c>(n + n^2)/2</c> only where <c>n >= 0</c>, the range being empty and the sum
6978+
/// <c>0</c> below that while the polynomial is not.
6979+
/// </para>
69726980
/// </remarks>
69736981
/// <example>
69746982
/// <code>

‎Sources/AngouriMath/Docs/Usage/Comparison.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -248,6 +248,21 @@ Long answers are truncated in the table below at 64 characters, with `…`.
248248
| holonomic | holonomic functions | `expr_to_holonomic exists: True` | `<no member at all matching "Holonomic">` | absent |
249249
| codegen | compile to a callable | `9` | `9` | answers |
250250

251+
### One row has moved since the run
252+
253+
**concrete / symbolic summation** was measured as `declines` at `6b93b401` and is answered now:
254+
`sum(k, k, 1, n)` is `(n + n^2)/2`, carrying the condition `n >= 0` that this library's
255+
empty-range convention requires and SymPy's reversed-range convention does not. The row is left
256+
as it was measured rather than edited, because the table is a record of one run at one commit and
257+
a hand-corrected cell would be a measurement nobody took; it will read `answers` when
258+
`sympyparity` is next run.
259+
260+
The two rows either side of it have **not** moved. *Infinite series* is still declined —
261+
`sum(1 / k ^ 2, k, 1, +oo)` needs the zeta function, which the row four below records as absent.
262+
*Symbolic product* is still declined, and deliberately: `factorial(n)` is undefined at the
263+
negative integers where the empty product is `1`, so answering it needs a condition of the same
264+
kind the sum now carries.
265+
251266
### Implemented, but not reachable from outside
252267

253268
The gap in these five is a public entry point, not an algorithm.

‎Sources/AngouriMath/Docs/Usage/Syntax.md‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,16 @@ name being declared and the first is the body it runs over, so `sum(i, i, 1, 10)
247247

248248
Both bounds are inclusive and the step is one. An empty range is the operator's identity —
249249
`sum(k, k, 5, 1)` is `0` and `product(k, k, 5, 1)` is `1` — and the range is written out only when
250-
both bounds are integers, so `sum(k, k, 1, n)` and `sum(k, k, 1, 5/2)` stay as they are written.
250+
both bounds are integers and there are not too many terms.
251+
252+
A `sum` whose body is a **polynomial in the index** is answered in closed form instead of being
253+
written out, so `sum(k, k, 1, n)` is `(n + n^2)/2` and `sum(k, k, 1, 100000)` is `5000050000`
254+
rather than a hundred thousand terms. The answer carries the condition it needs — `to >= from - 1`
255+
— because below that the range is empty and the polynomial is not zero; where the bounds are
256+
concrete that condition is decidable and the answer is a number. A bound that is a number and not
257+
a whole one still stays as written, since the index runs over the integers and
258+
`sum(k, k, 1, 5/2)` is `1 + 2` rather than the polynomial at `5/2`. A `product` stays as written
259+
whatever its body.
251260

252261
**The declared name means the name, and only inside the operator that declares it.** Two names
253262
show this, because both mean something else in this language:
Lines changed: 217 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,217 @@
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

Comments
 (0)