Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,38 @@ A not-equal written `<>` is read as `not (a = b)`, and printed that way.

## Unreleased — since 2.10.0

### Evaluation keeps its digits from 1e-100000 to 1e100000

**Silent: wrong numbers become right ones.** The decimals evaluation works in had a hundred digits, but exponents only
from -100 to 1000. An exact part below `10^-100` was 0 as a decimal, and one past `10^1000` was `+oo`, so every digit
built on such a part was wrong: `sqrt(1/10^200 + 1/10^210) * 10^100` was 0, and the exact roots `Solve` writes for an
equation in `10^20 x` evaluated to points that are not roots. The exponents now run from -100000 to 100000. The sine,
cosine and arctangent of a tiny argument are summed as series in floating point, where their fixed point had no digits
left. The sine and cosine of a large argument are reduced by `2 pi` taken to as many more digits as the argument has
before its point, and an exact rational argument is written out to that many digits too. Before, `sin(10^500)` had no
right digit. A caller that sets its own `DecimalPrecisionContext` keeps that context's range. Measured on 2.10.0 and on
this branch ([#2668](https://github.com/asc-community/AngouriMath/issues/2668)).

| `.Evaled` | Was (2.10.0) | Now |
|---|---|---|
| `sqrt(1/10^200 + 1/10^210) * 10^100` | `0` | `1.00000000004999999999875…` |
| `sqrt(10^(-300)) * 10^150` | `0` | `1` |
| `(1/10^200 + i/10^200) * 10^200` | `1` | `1 + i` |
| `2^(-1000) * sqrt(2) * 2^1000` | `0` | `1.41421356237309504880…` |
| `exp(-1000)` | `0` | `5.07595889754945676529…E-435` |
| `exp(3000)` | `+oo` | `7.64620098905470488931…E+1302` |
| `exp(3000) * exp(-3000)` | `NaN` | `1` |
| `sin(1/10^200) * 10^200`, and `arctan` | `0` | `1` |
| `sin(10^60)` | `0.83038976521934266466…8514636898040…`, wrong from the 49th digit | `…8514630714107…` |
| `sin(10^500)` | `-0.27853856742087907707…` | `0.31102693090790028047…` |
| `sin(2^1000)` | `0.29150829785727846625…` | `-0.15920170308624243824…` |
| `cos(10^5000)` | `NaN` | `-0.72745055141283323318…` |
| `gamma(316 * i)` | `0` | `3.55632285366604152450…E-217 + 1.28845172909637752912…E-217i` |
| `catalannumber(2000.5)` | `+oo` | `1.66144399474248826784…E+1199` |
| `(1e600 + 1e600 * i)^2` | `+ooi` | `2.000…E+1200i` |

The range still ends: `exp(-240000)` is 0 and `(1 + i)^(10^6)` is `+oo`, and a comparison of two such sides stays written.

### A number past the working digits is not taken for an exact one

**Not silent: wrong answers become exact ones.** At the default hundred digits, a product past about `10^50`
Expand Down Expand Up @@ -83,8 +115,9 @@ before v3, which decides exact comparisons exactly (#1019 §10). Two decimals th
| `10^(-200) < 2 * 10^(-200)` | `False` | `True` |
| `1000! * 2 < 1001!` | `False` | `True` |
| `10^(590) >= 10^(590) + 10^(440)` | `True` | `False` |
| `exp(-1000.5) > exp(-3002.5)` | `False` | stays written |
| `exp(-2000) = exp(-2000.5)` | `True` | stays written |
| `exp(-1000.5) > exp(-3002.5)` | `False` | `True`, both sides within the exponents since [#2668](https://github.com/asc-community/AngouriMath/issues/2668) |
| `exp(-2000) = exp(-2000.5)` | `True` | `False`, likewise |
| `exp(-240000) = exp(-240000.5)` | `True` | stays written |
| `sqrt(5)^1000 = 5^500` | `False` | stays written |
| `sqrt(2) < sqrt(2) + 10^(-150)` | `False` | stays written |

Expand Down
8 changes: 7 additions & 1 deletion Sources/AngouriMath/Convenience/MathS.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6776,8 +6776,14 @@ internal static EDecimal DowncastingTolerance
/// <summary>
/// Settings for <see cref="EDecimal"/> precisions of <a href="https://github.com/peteroupc/Numbers">PeterO.Numbers</a>
/// </summary>
/// <remarks>
/// A hundred digits, at any magnitude from 1e-100000 to 1e100000. The exponents ended at -100 and
/// 1000, so that an exact part below 1e-100 was 0 as a decimal and every digit built on it was
/// wrong: <c>sqrt(1/10^200 + 1/10^210) * 10^100</c> was 0, and <c>exp(3000) * exp(-3000)</c> was
/// NaN. https://github.com/asc-community/AngouriMath/issues/2668
/// </remarks>
public static Setting<EContext> DecimalPrecisionContext { get; } =
new(new EContext(100, ERounding.HalfUp, -100, 1000, false));
new(new EContext(100, ERounding.HalfUp, -100000, 100000, false));

/// <summary>
/// Whether functions are being read as real-valued or complex-valued. It is a
Expand Down
30 changes: 24 additions & 6 deletions Sources/AngouriMath/Core/Entity/Continuous/Number/Operators.cs
Original file line number Diff line number Diff line change
Expand Up @@ -953,12 +953,28 @@ private static (EDecimal Sinh, EDecimal Cosh) SinhAndCosh(EDecimal y, EContext c
return (p.Subtract(q, work).Divide(2, work).RoundToPrecision(context), p.Add(q, work).Divide(2, work).RoundToPrecision(context));
}

/// <summary>
/// The argument a periodic function reduces: <paramref name="written"/>, the number's decimal, but for a
/// rational past <c>10^8</c> its decimal to as many more digits as it has before its point, which the
/// reduction by <c>2 pi</c> takes away. In the context's digits alone <c>2^1000</c> is known to 1e202,
/// and <c>sin(2^1000)</c> came back 0.29 where it is -0.16.
/// https://github.com/asc-community/AngouriMath/issues/2668
/// </summary>
private static EDecimal PeriodicArgument(Real real, EDecimal written, EContext context)
{
if (real is not Rational { ERational: var exact } || !written.IsFinite || written.CompareToTotalMagnitude(tenToTheEight) < 0)
return written;
var magnitude = written.Exponent.Add(written.Precision()).ToInt32Checked();
return exact.ToEDecimal(EContext.ForPrecision(context.Precision.ToInt32Checked() + magnitude + 16).WithUnlimitedExponents());
}
[ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8");

/// <summary>Calculates the exact value of sine of num</summary>
public static Complex Sin(Complex num)
{
var context = MathS.Settings.DecimalPrecisionContext;
if (num is Real { EDecimal: var real })
return Real.CreateAtScale(real.Sin(context), real);
if (num is Real { EDecimal: var real } asReal)
return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Sin(context), real);
// From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1
var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal);
var (sinh, cosh) = SinhAndCosh(im, context);
Expand Down Expand Up @@ -1019,8 +1035,8 @@ public static Real Abs(Complex num)
public static Complex Cos(Complex num)
{
var context = MathS.Settings.DecimalPrecisionContext;
if (num is Real { EDecimal: var real })
return Real.CreateAtScale(real.Cos(context), real);
if (num is Real { EDecimal: var real } asReal)
return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Cos(context), real);
// From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1
var (re, im) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal);
var (sinh, cosh) = SinhAndCosh(im, context);
Expand All @@ -1036,8 +1052,8 @@ public static Complex Cos(Complex num)
public static Complex Tan(Complex num)
{
var context = MathS.Settings.DecimalPrecisionContext;
if (num is Real { EDecimal: var real })
return Real.CreateAtScale(real.Tan(context), real);
if (num is Real { EDecimal: var real } asReal)
return Real.CreateAtScale(PeriodicArgument(asReal, real, context).Tan(context), real);
// From https://source.dot.net/#System.Runtime.Numerics/System/Numerics/Complex.cs,cf15f2e5cc49cef1

// tan z = sin z / cos z, but to avoid unnecessary repeated trig computations, use
Expand Down Expand Up @@ -1084,6 +1100,8 @@ public static Complex Cotan(Complex num)
var (x, y) = (num.RealPart.EDecimal, num.ImaginaryPart.EDecimal);
if (!x.IsFinite || !y.IsFinite)
return Integer.One / Tan(num);
if (num is Real asReal)
x = PeriodicArgument(asReal, x, context);
var (sin, cos) = (x.Sin(context), x.Cos(context));
// sin x is a residual of x as on the real line, and 0 at a pole: cot of pi to the working digits is NaN.
if (y.IsZero)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2558,6 +2558,7 @@ is var (multiple, leftover)
// reached the same answer through them after seventeen seconds of peeling and
// re-factoring; this way it is under a second.
if (Mulf.LinearChildren(denominator).Any(f => f.ContainsNode(x) && f is Powf(_, Number.Integer { EInteger.Sign: > 0 } e) && e != Number.Integer.One)
&& !TwoBinomialsPastTheSecondDegree(denominator, x)
&& IntegrateByAnsatz(null, numerator / denominator, x) is { } byHermite)
return byHermite;

Expand Down Expand Up @@ -3297,6 +3298,30 @@ private static Entity WithTheDenominatorInPowersOf(Entity value, IReadOnlyList<E
return above / (remaining == Number.Integer.One ? powers : remaining * powers);
}

/// <summary>
/// Whether <paramref name="denominator"/> has two factors, each written once or as a power,
/// that are binomials of degree three or four in <paramref name="x"/>. Over two such
/// binomials with symbols in them the Hermite reduction's system answers in coefficients
/// pages long -- <c>x^7 (a + b x^3)^(1/3)/(c + d x^3)</c>, which the cube root's
/// substitution makes one over <c>(u^3 - 1/b)^3</c> and <c>c + (a d - b c) u^3</c>, came back
/// in 23,030 characters with <c>c^50</c> in them, where the rules for the cube root write
/// 2,861. The split by residues declines the same pair for the same reason. Over 1e1000 the
/// check of that answer used to overflow, which declined it by accident.
/// https://github.com/asc-community/AngouriMath/issues/2668
/// </summary>
private static bool TwoBinomialsPastTheSecondDegree(Entity denominator, Entity.Variable x)
{
var binomials = 0;
foreach (var factor in Mulf.LinearChildren(denominator))
{
var written = factor is Powf(var @base, Number.Integer { EInteger.Sign: > 0 }) ? @base : factor;
if (written.ContainsNode(x) && TreeAnalyzer.TryGetPolynomial(written, x, out var read)
&& read.Count == 2 && read.Keys.Max() is { } degree && (degree.Equals(EInteger.FromInt32(3)) || degree.Equals(EInteger.FromInt32(4))))
binomials++;
}
return binomials > 1;
}

/// <summary>
/// <c>N/(B_1 ... B_m)</c> where every block <c>B_i</c> is a polynomial in <c>x^n</c> for one
/// <c>n >= 2</c>, linear or quadratic in it, with a symbol among them: split in
Expand Down
76 changes: 76 additions & 0 deletions Sources/AngouriMath/Functions/InternalAMExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,39 @@ internal static EContext WithUnboundedExponents(EContext context)
/// </remarks>
internal static (EDecimal Sin, EDecimal Cos) SinAndCos(EDecimal x, EContext context)
{
// Reduced below by a multiple of 2 pi in pi's working digits, whose error the multiple
// scales: from 10^8 on that is more than the guard digits, and sin(10^500) had none of
// its digits right. So the reduction is done first with pi to as many more digits as
// the argument has before its point. https://github.com/asc-community/AngouriMath/issues/2668
if (x.CompareToTotalMagnitude(tenToTheEight) >= 0)
return SinAndCos(ReducedByTwoPi(x, context.Precision.ToInt32Checked() + x.Exponent.Add(x.Precision()).ToInt32Checked()), context);
var working = WithGuardDigits(context, 8);
if (x.CompareToTotalMagnitude(belowEightGuardDigits) < 0)
{
// Fixed point carries the eight guard digits as absolute precision, so below
// 10^-8 a sine would come back short of the context's digits, and at 10^-200 as
// 0. The two series in floating point instead, a handful of terms each.
// https://github.com/asc-community/AngouriMath/issues/2668
var xSquared = x.Multiply(x, working);
var smallSin = x;
var smallCos = EDecimal.One;
var sinPower = x;
var cosPower = EDecimal.One;
for (var k = 1; k < 100000; k++)
{
cosPower = cosPower.Multiply(xSquared, working).Divide(-(2 * k - 1) * (2 * k), working);
sinPower = sinPower.Multiply(xSquared, working).Divide(-(2 * k) * (2 * k + 1), working);
var nextSin = smallSin.Add(sinPower, working);
var nextCos = smallCos.Add(cosPower, working);
// Compared as numbers: a zero's terms are zeros of ever smaller exponents, which
// differ from each other as representations.
if (nextSin.CompareTo(smallSin) == 0 && nextCos.CompareTo(smallCos) == 0)
break;
smallSin = nextSin;
smallCos = nextCos;
}
return (smallSin.RoundToPrecision(context), smallCos.RoundToPrecision(context));
}
var consts = ConstantCache.Lookup(working);
var bits = consts.FixedBits;
var one = consts.FixedOne;
Expand Down Expand Up @@ -596,6 +628,28 @@ internal static (EDecimal Sin, EDecimal Cos) SinAndCos(EDecimal x, EContext cont
return (FromFixed(sin, consts, working).RoundToPrecision(context), FromFixed(cos, consts, working).RoundToPrecision(context));
}

/// <summary>
/// <paramref name="x"/> less the multiple of <c>2 pi</c> nearest it, to about
/// <paramref name="digits"/> less the digits <paramref name="x"/> has before its point, which
/// is <c>2 pi</c>'s error times the multiple. <c>2 pi</c> is made once for each 256 digits a
/// thread asks for: a thousand digits of it take milliseconds, and twenty thousand a second.
/// </summary>
private static EDecimal ReducedByTwoPi(EDecimal x, int digits)
{
var bucket = (digits + 32 + 255) / 256 * 256;
var held = twoPiByDigits ??= new();
if (!held.TryGetValue(bucket, out var entry))
{
var wide = EContext.ForPrecision(bucket).WithUnlimitedExponents();
entry = (wide, EDecimal.PI(wide).Multiply(2, wide));
held[bucket] = entry;
}
// Not RemainderNear, which is NaN for a quotient of five hundred digits.
var turns = x.Divide(entry.TwoPi, entry.Context).RoundToExponent(0, ERounding.HalfEven);
return x.Subtract(turns.Multiply(entry.TwoPi, entry.Context), entry.Context);
}
[ThreadStatic] private static Dictionary<int, (EContext Context, EDecimal TwoPi)>? twoPiByDigits;

/// <summary>Analogy of <see cref="Math.Tan(double)"/></summary>
public static EDecimal Tan(this EDecimal x, EContext context)
{
Expand Down Expand Up @@ -708,6 +762,25 @@ public static EDecimal Arctan(this EDecimal x, EContext context)
var working = WithGuardDigits(context, 5);
if (x.GreaterThan(EDecimal.One))
return ConstantCache.Lookup(working).HalfPi.Subtract(Arctan(EDecimal.One.Divide(x, working), working), working).RoundToPrecision(context);
if (x.CompareTo(belowFiveGuardDigits) < 0)
{
// Below 10^-5 the fixed point's absolute precision, five guard digits, would
// leave the arctangent short of the context's digits, and at 10^-200 it was 0;
// so the series in floating point, a handful of terms.
// https://github.com/asc-community/AngouriMath/issues/2668
var xSquared = x.Multiply(x, working);
var power = x;
var smallSum = x;
for (var k = 1; k < 100000; k++)
{
power = power.Multiply(xSquared, working).Negate();
var next = smallSum.Add(power.Divide(2 * k + 1, working), working);
if (next.CompareTo(smallSum) == 0)
break;
smallSum = next;
}
return smallSum.RoundToPrecision(context);
}

// In fixed point from here. The nearest sixty-fourth is exact in fixed point
// (FixedBits is at least six), so the table's entry is the arctangent of it.
Expand Down Expand Up @@ -978,6 +1051,9 @@ private static BigInteger TwiceArtanh(BigInteger y, int bits)
return sum << 1;
}

[ConstantField] private static readonly EDecimal tenToTheEight = EDecimal.FromString("1E+8");
[ConstantField] private static readonly EDecimal belowEightGuardDigits = EDecimal.FromString("1E-8");
[ConstantField] private static readonly EDecimal belowFiveGuardDigits = EDecimal.FromString("1E-5");
[ConstantField] private static readonly EDecimal sqrt2 = EDecimal.FromString("1.4142135623730950488");
[ConstantField] private static readonly EDecimal halfSqrt2 = EDecimal.FromString("0.70710678118654752440");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,14 +34,19 @@ public sealed class AComparisonOfExactNumbersIsExactTest
[InlineData("sqrt(2) < 3/2", true)]
[InlineData("exp(-300) > exp(-400)", true)]
[InlineData("10^(-20) = 2 * 10^(-20)", false)]
// A side was flushed to 0 or saturated to +oo, so these stayed written, until the exponents
// reached a hundred thousand. https://github.com/asc-community/AngouriMath/issues/2668
[InlineData("exp(-1000.5) > exp(-3002.5)", true)]
[InlineData("exp(6000) >= exp(6100)", false)]
[InlineData("exp(-2000) = exp(-2000.5)", false)]
public void TheComparisonIsDecided(string comparison, bool expected)
=> Assert.Equal(Boolean.Create(expected), comparison.ToEntity().Evaled);

/// <summary>Where the decimals cannot tell the sides apart, or made a side 0 or infinite, nothing is answered.</summary>
[Theory]
[InlineData("exp(-1000.5) > exp(-3002.5)")]
[InlineData("exp(6000) >= exp(6100)")]
[InlineData("exp(-2000) = exp(-2000.5)")]
[InlineData("exp(-100000.5) > exp(-300002.5)")]
[InlineData("exp(600000) >= exp(610000)")]
[InlineData("exp(-240000) = exp(-240000.5)")]
[InlineData("sqrt(2) < sqrt(2) + 10^(-150)")]
[InlineData("sqrt(5)^1000 = 5^500")]
public void AnUndecidedComparisonStaysWritten(string comparison)
Expand Down
Loading
Loading