Skip to content

Commit fb99ffe

Browse files
Evaluate an exact power too large to build as the decimal (#2347)
An exact number to a whole power was built exactly however large, so 46655^(10^20), which has 4.7e20 digits, neither returned nor stopped when cancelled, and nor did a simplification of anything holding it. Found by compilesweep on (x^x - 1)^(e^(e^x)) at 6; 2.6.0 does not finish it either. Past 2^24 bits the power is evaluated in the decimal context, as the same power with a half added already was: +oo past the range, -oo for an odd power of a negative base, 0 below it. The exact powers of -1, i and -i are unchanged, and so is every exact power that finishes today (3^(10^7) in 3.3 s). An exact simplification leaves such a power as written: an infinity counts as exact, so without a guard 2^(10^10) simplified to +oo. 46655^(10^20) now evaluates in 38 ms. The eight large cases each hit the 30 s cap on master and pass here. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent d41933e commit fb99ffe

4 files changed

Lines changed: 147 additions & 3 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,22 @@ and a number that passes every round is left open, since passing is not a proof
380380
| `"(10^30 + 1) in PP".ToEntity().Evaled` | `1000000000000000000000000000001 in PP` | `False` |
381381
| `"(10^30 + 57) in PP".ToEntity().Evaled` | `1000000000000000000000000000057 in PP` | `1000000000000000000000000000057 in PP` |
382382

383+
### An exact power too large to build is the decimal
384+
385+
**Not silent: what did not return now answers.** An exact number to a whole power was built exactly however large it
386+
was. `46655^(10^20)` has 4.7e20 digits, and its evaluation neither returned nor stopped when cancelled. Nor did a
387+
`Simplify` of anything holding it. Past sixteen million bits, about five million digits, a power is now evaluated as the
388+
decimal, as the same power with a half added already was: `+oo` past the context's range, `-oo` for a negative base to
389+
an odd power, and `0` below the range. An exact simplification leaves it as written, since the infinity is the
390+
decimal's. Each of -1, i and -i keeps its exact power. No issue was filed; a check of compiled expressions against
391+
evaluation found it.
392+
393+
| Input | Was (2.6.0) | Now |
394+
|---|---|---|
395+
| `"46655^(10^20)".EvalNumerical()` | does not return | `+oo` |
396+
| `"(5/2)^(10^7)".EvalNumerical()` | does not return | `+oo` |
397+
| `"2^(10^10)".Simplify()` | does not return | `2 ^ 10000000000` |
398+
383399
### A remainder of two ratios is exact
384400

385401
**Silent: a remainder that came back as the divisor, or as NaN, is the remainder.** `%` on `Real`, `mod` and evaluation

‎Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -586,6 +586,21 @@ static Complex BinaryIntPow(Complex num, EInteger val)
586586
return Integer.Zero;
587587
return infinite.IsNegative && !wholeOfInfinity.IsEven ? Real.NegativeInfinity : Real.PositiveInfinity;
588588
}
589+
// An exact power past MaxExactPowerBits is not built: 46655^(10^20) would have 4.7e20
590+
// digits, and the multiplications for it never returned or stopped when cancelled, so
591+
// a simplification of the expression did not either. It is the decimal, as the same
592+
// power with a half added is: +oo past the context's range, 0 below it.
593+
if (@base.IsFinite && pow is { } && IsTooLargeToBuild(@base, pow))
594+
{
595+
var largeContext = MathS.Settings.DecimalPrecisionContext;
596+
if (@base is Real { EDecimal: var realOfLarge })
597+
{
598+
var magnitude = PowerOfReals(realOfLarge.Abs(), EDecimal.FromEInteger(pow), largeContext);
599+
return Real.CreateAtScale(realOfLarge.IsNegative && !pow.IsEven ? magnitude.Negate() : magnitude, EDecimal.Zero);
600+
}
601+
return ByThePolarForm(@base.RealPart.EDecimal, @base.ImaginaryPart.EDecimal, @base.Abs().EDecimal,
602+
EDecimal.FromEInteger(pow), EDecimal.Zero, largeContext);
603+
}
589604
if (@base.IsFinite && pow is { })
590605
{
591606
// A real base that is not exact -- a decimal, which is what a numerical
@@ -680,7 +695,13 @@ static Complex BinaryIntPow(Complex num, EInteger val)
680695
if (baseReal.IsZero && baseImaginary.IsZero)
681696
return Integer.Zero;
682697

683-
var rho = @base.Abs().EDecimal;
698+
return ByThePolarForm(baseReal, baseImaginary, @base.Abs().EDecimal, powerReal, powerImaginary, context);
699+
}
700+
701+
/// <summary><c>base^power</c> by the polar form, for a base that is not 0 with modulus <paramref name="rho"/>.</summary>
702+
private static Complex ByThePolarForm(EDecimal baseReal, EDecimal baseImaginary, EDecimal rho,
703+
EDecimal powerReal, EDecimal powerImaginary, EContext context)
704+
{
684705
var theta = baseImaginary.Arctan2(baseReal, context);
685706
var newRho = powerReal.MultiplyAndAdd(theta, powerImaginary.Multiply(rho.NaturalLogarithm(context), context), context);
686707
var t = PowerOfReals(rho, powerReal, context).Multiply(powerImaginary.Multiply(-theta, context).Exponential(context), context);
@@ -690,6 +711,35 @@ static Complex BinaryIntPow(Complex num, EInteger val)
690711
return Complex.CreateAtScales(t.Multiply(newRho.Cos(context), context), t.Multiply(newRho.Sin(context), context), modulusScale, modulusScale);
691712
}
692713

714+
/// <summary>
715+
/// The most bits an exact power is built to: <c>3^(10^7)</c>, at 15.8 million, takes three seconds,
716+
/// and each doubling of the exponent doubles the size and more than doubles the time.
717+
/// </summary>
718+
[ConstantField] private static readonly EInteger MaxExactPowerBits = EInteger.FromInt32(1 << 24);
719+
720+
/// <summary>
721+
/// About how many bits an exact <paramref name="base"/> to the whole <paramref name="power"/> has: for
722+
/// each part of the base, the bits of its numerator and of its denominator past the first, the larger
723+
/// part's, and one more where both parts are not 0, times the power. Each of -1, i and -i has none,
724+
/// and a power of one is as small as it is. A base that is not exact is 0, being a decimal.
725+
/// </summary>
726+
internal static bool IsTooLargeToBuild(Complex @base, EInteger power)
727+
=> ExactPowerBits(@base, power).CompareTo(MaxExactPowerBits) > 0;
728+
729+
private static EInteger ExactPowerBits(Complex @base, EInteger power)
730+
{
731+
if (@base.RealPart is not Rational { ERational: var re } || @base.ImaginaryPart is not Rational { ERational: var im })
732+
return EInteger.Zero;
733+
static EInteger Bits(ERational part)
734+
=> part.IsZero ? EInteger.Zero
735+
: part.Numerator.Abs().GetUnsignedBitLengthAsEInteger().Subtract(1)
736+
.Add(part.Denominator.GetUnsignedBitLengthAsEInteger().Subtract(1));
737+
var bits = Bits(re).CompareTo(Bits(im)) >= 0 ? Bits(re) : Bits(im);
738+
if (!re.IsZero && !im.IsZero)
739+
bits = bits.Add(1);
740+
return bits.Multiply(power.Abs());
741+
}
742+
693743
/// <summary>e.g. Log(2, 32) = 5</summary>
694744
/// <param name="base">Log's base, log(base, x) is a number y such that base^y = x</param>
695745
/// <param name="x">The number of which we want to get its base power</param>

‎Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,19 @@ private static bool IsAZeroOnlyRoundingMade(Entity node, Entity value)
5555
=> value is Integer { IsZero: true }
5656
&& (node is Mulf or Divf or Powf && CannotBeZero(node) || node is Sumf or Minusf && SignOfANonzero(node) is not null);
5757

58+
/// <summary>
59+
/// Whether <paramref name="value"/> is an infinity that only the decimals made: an exact power too
60+
/// large to build is evaluated as a decimal, which is <c>+oo</c> past the context's range, and an
61+
/// infinity counts as exact, so that <c>2^(10^10)</c>, and every expression holding it, was
62+
/// simplified to <c>+oo</c>. Asked only of a value that is not finite.
63+
/// </summary>
64+
private static bool IsAnInfinityOnlyRoundingMade(Entity node, Entity value)
65+
=> value is Complex { IsFinite: false } && !value.IsNaN
66+
&& node.Nodes.Any(static part => part is Powf(var @base, var exponent)
67+
&& @base.Evaled is Complex { IsExact: true, IsFinite: true } exactBase
68+
&& exponent.Evaled is Integer { EInteger: var power }
69+
&& Number.IsTooLargeToBuild(exactBase, power));
70+
5871
/// <summary>
5972
/// Whether <paramref name="expr"/> is a number or a constant that is not zero, or a product,
6073
/// a quotient or a power of those with a finite divisor or exponent.
@@ -128,7 +141,8 @@ private Entity ExpandOnTwoArguments(
128141
bool propagateSet = true,
129142
bool settlesNaN = false)
130143
{
131-
if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n && !IsAZeroOnlyRoundingMade(this, n))
144+
if (isExact && this.Evaled is (Number { IsExact: true } or Boolean) and var n && !IsAZeroOnlyRoundingMade(this, n)
145+
&& !IsAnInfinityOnlyRoundingMade(this, n))
132146
return n;
133147
left = left.InnerSimplified(isExact);
134148
right = right.InnerSimplified(isExact);
@@ -151,7 +165,8 @@ Entity ops(Entity a, Entity b)
151165
{
152166
if (operation(a, b) is { } res)
153167
return res;
154-
if (isExact && defaultCtor(this, a, b) is var built && built.Evaled is Number { IsExact: true } n && !IsAZeroOnlyRoundingMade(built, n))
168+
if (isExact && defaultCtor(this, a, b) is var built && built.Evaled is Number { IsExact: true } n && !IsAZeroOnlyRoundingMade(built, n)
169+
&& !IsAnInfinityOnlyRoundingMade(built, n))
155170
return n;
156171
return defaultCtor(this, a, b);
157172
}
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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 System;
9+
using System.Threading.Tasks;
10+
using AngouriMath.Extensions;
11+
using Xunit;
12+
using static AngouriMath.Entity;
13+
using static AngouriMath.Entity.Number;
14+
15+
namespace AngouriMath.Tests.Core
16+
{
17+
/// <summary>
18+
/// An exact number to a whole power was built exactly however large, so <c>46655^(10^20)</c>, which has
19+
/// 4.7e20 digits, neither returned nor stopped when cancelled, and nor did a simplification of anything
20+
/// holding it. Past about sixteen million bits the power is now evaluated as the decimal, as the same
21+
/// power with a half added already was: <c>+oo</c> past the context's range. An exact simplification
22+
/// leaves it as written, since the infinity is the decimal's and not the power's. Found by compilesweep,
23+
/// on <c>(x^x - 1)^(e^(e^x))</c> at 6; no issue was filed.
24+
/// </summary>
25+
[Trait("Area", "Core")]
26+
public sealed class AnExactPowerTooLargeToBuildTest
27+
{
28+
[Theory]
29+
[InlineData("46655^(10^20)", "+oo")]
30+
[InlineData("46655^(e^(e^6))", "+oo")]
31+
[InlineData("(-3)^(10^20 + 1)", "-oo")]
32+
[InlineData("(-3)^(10^20)", "+oo")]
33+
[InlineData("(5/2)^(10^7)", "+oo")]
34+
// Each of -1, i and -i keeps its exact power, however large.
35+
[InlineData("i^(10^20)", "1")]
36+
[InlineData("(-1)^(10^20 + 1)", "-1")]
37+
[InlineData("(-i)^(10^20 + 3)", "i")]
38+
public void IsEvaluated(string input, string expected)
39+
=> Assert.Equal(expected.ToEntity().Evaled, Within(() => input.ToEntity().Evaled, input));
40+
41+
[Theory]
42+
[InlineData("2^(10^10)")]
43+
[InlineData("46655^(10^20) + 1")]
44+
[InlineData("(1/3)^(10^20)")]
45+
public void AnExactSimplificationLeavesItAsWritten(string input)
46+
{
47+
var simplified = Within(() => input.ToEntity().InnerSimplified, input);
48+
Assert.True(simplified is not Number, $"{input} was simplified to {simplified}");
49+
Assert.True(Within(() => input.ToEntity().Simplify(), input) is not Number, $"{input} was simplified to a number");
50+
}
51+
52+
[Fact]
53+
public void APowerBelowTheBoundIsStillExact()
54+
=> Assert.Equal(Integer.Create(PeterO.Numbers.EInteger.One.ShiftLeft(1000000)), Within(() => "2^(10^6)".ToEntity().Evaled, "2^(10^6)"));
55+
56+
private static Entity Within(Func<Entity> evaluation, string input)
57+
{
58+
var task = Task.Factory.StartNew(evaluation, TaskCreationOptions.LongRunning);
59+
Assert.True(task.Wait(TimeSpan.FromSeconds(30)), $"{input} did not finish in thirty seconds");
60+
return task.Result;
61+
}
62+
}
63+
}

0 commit comments

Comments
 (0)