Skip to content
Merged
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
25 changes: 25 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,31 @@ A not-equal written `<>` is read as `not (a = b)`, and printed that way.

## Unreleased — since 2.10.0

### 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`
evaluated to a decimal whose last digits had been rounded to 0. That decimal was taken for an integer, and `Simplify`
put it in place of the exact expression. So `2^340 * sqrt(2)` became a 103-digit integer, and
`sqrt(2)^800 / 2^400` became a fraction that is not 1. A rational past the decimals' exponent range also read as
not finite, so a product of one with `sqrt(2)` or `pi` simplified to `+oo` above that range and to `0` below it.

A value now becomes an integer or a small rational only if the working digits reach the downcasting tolerance below
its point. A large or small rational counts as finite when deciding whether evaluation alone made a zero or an
infinity. `Evaled` of such a product is now the decimal it always was, for example `3.167...E+102`, and not an
integer. Exact large integers are unchanged
([#2615](https://github.com/asc-community/AngouriMath/issues/2615)).

| | Was (2.10.0) | Now |
|---|---|---|
| `"2^340 * sqrt(2)".Simplify()` | `3167477390…7832751217000` | `2239744742…607115776 * sqrt(2)` |
| `"sqrt(2)^800 / 2^400".Simplify()` | `1231312693…/1231312693…`, not 1 | `1` |
| `"10^200 * pi / 10^199".Simplify()` | `7853981633…/2500000000…` | `10 * pi` |
| `"e^700".Simplify()` | `1014232054…` followed by about 200 zeros | `e ^ 700` |
| `"2^4000 * sqrt(2)".Simplify()` | `+oo` | `1318204093… * sqrt(2)` |
| `"2^(-20000) * sqrt(2)".Simplify()` | `0` | `sqrt(2) / 3980276840…` |
| `"integral(exp(x), x, 0, 300)".Simplify()` | `1942426395…4199999…9` | `e ^ 300 - 1` |
| `"2^340 * sqrt(2)".Evaled` | an `Integer` | `3.167477390…E+102`, a `Real` |

### A square system is answered exactly whichever order its equations are in

**Not silent: a decimal answer is now exact, and a refused system has an answer.** The eliminator took the last
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,11 +132,18 @@ private static Real Create(EDecimal value, bool fromMachineNumber, EDecimal canc
// https://github.com/asc-community/AngouriMath/issues/1338
if (!Rational.MayBeASmallRational(value, MathS.Settings.FloatToRationalIterCount, MathS.Settings.DowncastingToleranceAsDouble))
return new Real(value);
var tolerance = MathS.Settings.DowncastingTolerance;
// A value whose working digits do not reach the tolerance below its point is no integer and no small
// rational, however its decimal happens to end: at a hundred digits, 2^340 sqrt(2) is 103 digits
// long, its last three rounded to 0, and it was taken for an integer, which Simplify then put in
// place of the exact product. https://github.com/asc-community/AngouriMath/issues/2615
// A machine number's digits are all exact, however many there are, and it is not asked this.
if (!fromMachineNumber && !WorkingDigitsReachTheTolerance(value, tolerance))
return new Real(value);
var (intPart, intRest) = value.SplitDecimal();
// If the difference between value & round(value) is zero (see Number.IsZero), we consider value as an integer.
// Onto zero only as a residual of the cancellation that produced it, below the tolerance times the
// scale of what cancelled; a negative one reaches zero by rounding up.
var tolerance = MathS.Settings.DowncastingTolerance;
bool IsAResidual() => value.IsZero || !cancelledScale.IsZero && value.Abs().LessThan(tolerance.Multiply(cancelledScale.Abs()));
if (intRest.LessThan(tolerance) && (!intPart.IsZero || IsAResidual()))
return Integer.Create(intPart);
Expand All @@ -152,6 +159,37 @@ private static Real Create(EDecimal value, bool fromMachineNumber, EDecimal canc
return attempt;
}

/// <summary>
/// Whether the working precision places <paramref name="value"/>'s digits down to
/// <paramref name="tolerance"/>: its magnitude is below the tolerance times ten to the precision. Always
/// where the precision is unlimited.
/// </summary>
private static bool WorkingDigitsReachTheTolerance(EDecimal value, EDecimal tolerance)
{
var precision = MathS.Settings.DecimalPrecisionContext.Value.Precision;
if (precision.IsZero)
return true;
// In doubles first, which allocate nothing: every number the parser reads comes through here, and
// building ten to the precision for each was 7% more bytes on parsing "1 + 2 / x + 2 / (y + x)".
// A magnitude a digit or more either side of the bound is decided; only one near it is compared exactly.
if (precision.CanFitInInt32())
{
var magnitude = System.Math.Abs(value.ToDouble());
var toleranceAsDouble = MathS.Settings.DowncastingToleranceAsDouble;
if (magnitude == 0)
return true;
if (magnitude < double.PositiveInfinity && toleranceAsDouble > 0)
{
var digitsPast = System.Math.Log10(magnitude) - (System.Math.Log10(toleranceAsDouble) + precision.ToInt32Unchecked());
if (digitsPast < -1)
return true;
if (digitsPast > 1)
return false;
}
}
return value.Abs().LessThan(tolerance.Multiply(EDecimal.Create(EInteger.One, precision)));
}

/// <inheritdoc/>
/// <remarks>
/// Made at a scale of zero, as <see cref="Complex.Abs"/> is: a number that is not 0 has a
Expand Down
25 changes: 20 additions & 5 deletions Sources/AngouriMath/Functions/Evaluation/Evaluation.Classes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,14 +63,21 @@ private static bool IsAZeroOnlyRoundingMade(Entity node, Entity value)
/// infinite as evaluated. An infinity counts as exact, and every expression holding one was simplified to
/// it. An operand that is a decimal already is not asked about: its power past the range is the
/// decimal's <c>+oo</c>, as it was. Asked only of a value that is not finite.
/// <para>
/// An operand written exactly whose value is a decimal, <c>sqrt(2)</c> or <c>pi</c>, is finite all the same:
/// <c>2^4000 sqrt(2)</c> is about <c>1.9e1204</c>, past the range, and its <c>+oo</c> was taken as the
/// value of the product, so <c>Simplify</c> answered <c>+oo</c>.
/// https://github.com/asc-community/AngouriMath/issues/2615
/// </para>
/// </summary>
private static bool IsAnInfinityOnlyRoundingMade(Entity node, Entity value)
=> value is Complex number && !Number.PartsAreFinite(number) && !value.IsNaN && node.Nodes.Any(IsFiniteRoundedOntoAnInfinity);

private static bool IsFiniteRoundedOntoAnInfinity(Entity part)
=> part is Sumf or Minusf or Mulf or Powf
&& part.Evaled is Complex { IsFinite: false } evaluated && !evaluated.IsNaN
&& part.DirectChildren.All(static operand => operand.Evaled is Complex { IsFinite: true, IsExact: true })
&& part.DirectChildren.All(static operand => operand.Evaled is Complex finite && IsFiniteExactly(finite)
&& (finite.IsExact || !operand.Nodes.Any(static node => node is Number { IsExact: false })))
&& !(part is Powf(var @base, _) && @base.Evaled is Complex { IsZero: true });

/// <summary>
Expand All @@ -79,14 +86,22 @@ private static bool IsFiniteRoundedOntoAnInfinity(Entity part)
/// </summary>
private static bool CannotBeZero(Entity expr) => expr switch
{
Complex number => !number.IsZero && number.IsFinite,
Variable { IsConstant: true } constant => constant.Evaled is Complex { IsZero: false, IsFinite: true },
Complex number => !number.IsZero && IsFiniteExactly(number),
Variable { IsConstant: true } constant => constant.Evaled is Complex { IsZero: false } value && IsFiniteExactly(value),
Mulf(var left, var right) => CannotBeZero(left) && CannotBeZero(right),
Divf(var dividend, var divisor) => CannotBeZero(dividend) && divisor.Evaled is Complex { IsFinite: true },
Powf(var @base, var exponent) => CannotBeZero(@base) && exponent.Evaled is Complex { IsFinite: true },
Divf(var dividend, var divisor) => CannotBeZero(dividend) && divisor.Evaled is Complex value && IsFiniteExactly(value),
Powf(var @base, var exponent) => CannotBeZero(@base) && exponent.Evaled is Complex value && IsFiniteExactly(value),
_ => SignOfANonzero(expr) is not null
};

/// <summary>
/// Whether <paramref name="number"/> is finite, a rational however large among them: <c>IsFinite</c> reads a
/// rational through the decimals, and <c>2^3400</c> is past their range there, so <c>sqrt(2) / 2^3400</c>, which
/// evaluates to 0, was not known to be a quotient that cannot be 0, and <c>Simplify</c> answered 0.
/// https://github.com/asc-community/AngouriMath/issues/2615
/// </summary>
private static bool IsFiniteExactly(Complex number) => number is Rational || number.IsFinite;

/// <summary>
/// The sign of <paramref name="expr"/> where it is a real number or a constant that is not
/// zero, or a product, a quotient, a power or a sum of those whose sign the parts decide;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,16 @@ private bool IsEvenRoot
=> Exponent is Rational and not Integer and Rational ratio
&& ratio.ERational.Denominator.Remainder(2).IsZero;

/// <summary>
/// Whether an exact <paramref name="base"/> to a decimal <paramref name="exponent"/> would be a power too
/// large to build were the exponent the whole number just past it.
/// </summary>
private static bool IsTooLargeToBuild(Complex @base, PeterO.Numbers.EDecimal exponent)
=> exponent.IsFinite
&& exponent.Abs().CompareTo(PeterO.Numbers.EDecimal.FromInt64(1L << 40)) >= 0
? Number.IsTooLargeToBuild(@base, PeterO.Numbers.EInteger.One.ShiftLeft(41))
: exponent.IsFinite && Number.IsTooLargeToBuild(@base, exponent.Abs().ToEInteger().Add(PeterO.Numbers.EInteger.One));

/// <summary>
/// Whether an exact <paramref name="base"/> to the rational <paramref name="exponent"/> is past the size an
/// exact power is built to, a fraction <c>p / q</c> read as the whole power just above <c>|p / q|</c>: a
Expand Down Expand Up @@ -531,6 +541,11 @@ protected override Entity InnerSimplify(bool isExact) =>
// what can be said of it is said by structure or by its exponent, and the rest is
// left undecided. https://github.com/asc-community/AngouriMath/issues/1448
(Complex n1, Rational n2) when IsTooLargeToBuild(n1, n2) => null,
// So is one whose exponent is a decimal that large: e^(e^6), about 1e175, is a decimal,
// and 46655 to it is no more +oo than 46655^(10^20) is. Until a decimal that large was
// taken for an integer it reached the arm above.
// https://github.com/asc-community/AngouriMath/issues/2615
(Complex n1, Real { EDecimal: var large } n2) when n2 is not Rational && IsTooLargeToBuild(n1, large) => null,
(Complex n1, Complex n2) when !isExact => Number.Pow(n1, n2), // returns 1 for 0^0 and 0 for 0^(negative real part), we need to handle these cases above
(Integer(1), { DomainCondition: var condition }) => Integer.One.Provided(condition),
(var n1, Integer(-1)) => (1 / n1).InnerSimplified(isExact),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
//
// Copyright (c) 2019-2026 Angouri.
// AngouriMath is licensed under MIT.
// Details: https://github.com/asc-community/AngouriMath/blob/master/LICENSE.md.
// Website: https://am.angouri.org.
//

using System.Linq;
using AngouriMath.Extensions;
using Xunit;
using static AngouriMath.Entity;

namespace AngouriMath.Tests.Common
{
/// <summary>
/// An exact integer times an irrational past the working digits simplified to a rounded number. Past about
/// <c>10^100</c> the decimal of the product, its last digits rounded to 0, was taken for an integer, so
/// <c>2^340 sqrt(2)</c> simplified to a 103-digit integer. Past the decimals' exponent range the product was
/// <c>+oo</c> and below it <c>0</c>, because a rational that large or that small reads as not finite through the
/// decimals, and the guards against such roundings asked exactly that.
/// https://github.com/asc-community/AngouriMath/issues/2615
/// </summary>
[Trait("Area", "Common")]
public sealed class AnExactProductPastTheWorkingDigitsStaysExactTest
{
[Theory]
[InlineData("2^340 * sqrt(2)", "sqrt(2)")]
[InlineData("2^400 * pi", "pi")]
[InlineData("10^200 * sqrt(2)", "sqrt(2)")]
[InlineData("2^4000 * sqrt(2)", "sqrt(2)")]
[InlineData("2^(-20000) * sqrt(2)", "sqrt(2)")]
[InlineData("sqrt(2) / 2^3400", "sqrt(2)")]
[InlineData("2^(-3400) * pi", "pi")]
public void TheIrrationalFactorIsKept(string expression, string irrational)
{
var simplified = expression.ToEntity().Simplify();
Assert.False(simplified is Number, $"{expression} simplified to the number {simplified}");
Assert.Contains(simplified.Nodes, node => node == irrational.ToEntity());
// And the same multiple of it, exactly: with the irrational a variable, the difference is 0.
Variable t = "t";
var difference = (simplified.Substitute(irrational.ToEntity(), t) - expression.ToEntity().Substitute(irrational.ToEntity(), t)).Simplify();
Assert.Equal(Number.Integer.Zero, difference);
}

/// <summary>A rounded decimal that large is no integer when evaluated either.</summary>
[Fact]
public void TheEvaluatedValueIsADecimal()
=> Assert.IsNotType<Number.Integer>("2^340 * sqrt(2)".ToEntity().Evaled);

/// <summary>Exact arithmetic on large integers and their values is unchanged.</summary>
[Theory]
[InlineData("2^340 * 2", "2^341")]
[InlineData("sqrt(2)^400", "2^200")]
[InlineData("2^4000 * 3 - 2^4000 * 2", "2^4000")]
public void AnExactIntegerStaysAnInteger(string expression, string expected)
=> Assert.Equal(expected.ToEntity().InnerSimplified, expression.ToEntity().Simplify());
}
}
Loading