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
19 changes: 19 additions & 0 deletions BREAKING-CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,25 @@ one point, or else `Simplify` proving it zero. A singular matrix answers as `[[1
| `"[[sin(x)^2, 1], [1 - cos(x)^2, 1]]^(-1)".Simplify()` | `NaN` | `1 / [[sin(x) ^ 2, 1], [sin(x) ^ 2, 1]]` |
| `"[[e^x, e^(2x)], [2, e^x]]^(-1)".Simplify()` | its inverse | unchanged |

### A real root beside a pole is found by the numeric search

**More roots in the same finite set.** Where no analytical route answers, `Solve` gives the roots Newton's method
finds, started from a grid and from each sign change of a scan of the real line, points 0.2 apart. A root with no
sign change between it and the next point of that scan was left to the grid, which missed it: one beside a pole,
`tan(x) = 2x` at 4.6042, or beside a point the expression has no value at, `1/gamma(x) = x/10` at -8.9999975, 2.5e-6
from the pole of `gamma` at -9. The scan now halves an interval where its midpoint does not lie between the values
at its ends, or has none, and runs Newton's method from each sign change that turns up
([#2545](https://github.com/asc-community/AngouriMath/issues/2545)). Every root added is a root, checked as before.
The answer can still be short of roots, as any Newton answer can.

| Input | Was (2.10.0) | Now |
|---|---|---|
| `"tan(x) = 2x".ToEntity().Solve("x")` | five real roots | seven: `±4.6042…` as well |
| `"x tan(x) = 28".ToEntity().Solve("x")` | nine real roots | eleven: `±1.5167…` as well |
| `"1/gamma(x) = x/10".ToEntity().Solve("x")` | one real root, 3.3901, and eight non-real | ten real: `-8.9999975…`, `-8.0000198…`, `-6.9998611…`, `-6.0008322…`, `-4.9958068…`, `-4.0163347…`, `-2.9472967…`, `-2.0971912…`, `-0.9046748…` as well |
| `"gamma(x) - 1".ToEntity().SolveNt("x")` | real roots 1 and 2 | ten real: the two of `gamma(x) = 1` in each of `(-10, -9)`, `(-8, -7)`, `(-6, -5)` and `(-4, -3)` as well |
| `"x! - x".ToEntity().SolveNt("x")` | real roots -3.9553, 1 and 2 | the same ten as `gamma(x) - 1` |

### A root near 0 of an equation in tanh, sinh or cosh is not a near copy of 0

**Not silent: a false root is gone.** tanh, sinh and cosh are written with exponentials, and near 0 the parts of
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -435,6 +435,9 @@ private static IEnumerable<NumericsComplex> RealSignChanges(
yield break;
var from = settings.From.Re.ToDouble();
var to = settings.To.Re.ToDouble();
var starts = new List<double>();
// What the closer look below may spend, in evaluations, beyond the scan itself.
var budget = CloserLookBudget * count;
var previousAt = double.NaN;
double? previous = null;
for (long i = 0; i <= count; i++)
Expand All @@ -443,9 +446,22 @@ private static IEnumerable<NumericsComplex> RealSignChanges(
var at = from * share + to * (1 - share);
var value = RealValueAt(at);
if (value is 0d)
yield return new NumericsComplex(at, 0);
else if (value is { } here && previous is { } there
&& (here < 0) != (there < 0))
starts.Add(at);
else if (i > 0)
Bracket(previousAt, previous, at, value, 0);
previousAt = at;
previous = value;
}
foreach (var start in starts)
yield return new NumericsComplex(start, 0);

// The starting points [a, b] holds: the bracket halved down to its root where the
// values at the ends differ in sign, and otherwise a closer look where the scan cannot
// say there is none.
void Bracket(double a, double? atA, double b, double? atB, int depth)
{
if (atA is { } valueA && atB is { } valueB && (valueA < 0) != (valueB < 0))
{
// The bracket halved down to the root, rather than its midpoint: the
// bracket holds a root and Newton converges fastest from as near it as we
// can say it is. From the midpoint it could not converge at all where the
Expand All @@ -454,12 +470,55 @@ private static IEnumerable<NumericsComplex> RealSignChanges(
// 3.7913, and from 3.7 the iteration went off the real line and its one
// real root was never answered. A pole between the two is halved down to as
// well, and its value there rejects it as it did before.
yield return new NumericsComplex(Halved(previousAt, there, at, RealValueAt), 0);
previousAt = at;
previous = value;
starts.Add(Halved(a, valueA, b, RealValueAt));
return;
}
if (depth >= CloserLookDepth || budget <= 0)
return;
// Two ends of one sign, or an end where the expression has no real value, can still
// hold roots: two of them, or one beside a pole or beside a point the expression is
// not defined at, the scan's resolution of 0.2 cannot tell apart. tan(x) = 2x is
// -0.34 at 4.6 and -21 at 4.8, and between them are its root at 4.6042 and the pole
// at 3pi/2; 1/gamma(x) = x/10 has no value at -9 and its root is 2.5e-6 from it.
// So the interval is halved where its midpoint says the expression does not just
// go from one end's value to the other's: it changes sign there, has no real value
// there, or is nearer 0 or further from it than both ends. Only the halves that
// say so again are halved further, so a smooth stretch costs one evaluation and
// each root or pole a chain down to CloserLookDepth.
// https://github.com/asc-community/AngouriMath/issues/2545
var middle = (a + b) / 2;
budget--;
var atMiddle = RealValueAt(middle);
if (atMiddle is 0d)
{
starts.Add(middle);
return;
}
var worthHalving = atA is not { } endA || atB is not { } endB
? atA is not null || atB is not null || atMiddle is not null
: atMiddle is not { } m
|| (m < 0) != (endA < 0)
|| Math.Abs(m) < Math.Min(Math.Abs(endA), Math.Abs(endB))
|| Math.Abs(m) > Math.Max(Math.Abs(endA), Math.Abs(endB));
if (!worthHalving)
return;
Bracket(a, atA, middle, atMiddle, depth + 1);
Bracket(middle, atMiddle, b, atB, depth + 1);
}
}

/// <summary>
/// How many times an interval of the real scan may be halved for a closer look: from the
/// default spacing of 0.2, down to about 1e-8.
/// </summary>
private const int CloserLookDepth = 24;

/// <summary>
/// The evaluations the closer look may spend, per point of the real scan, so that an
/// expression that oscillates without end, <c>sin(1/x)</c> near 0, cannot halve without end.
/// </summary>
private const int CloserLookBudget = 16;

/// <summary>
/// A point of <c>[low, high]</c>, or <c>[high, low]</c>, as near a sign change of
/// <paramref name="valueAt"/> as halving the interval gets in double precision, given
Expand Down
41 changes: 41 additions & 0 deletions Sources/Tests/UnitTests/Common/SolverRegressionTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -514,10 +514,10 @@
var unknowns = variables.Split(',').Select(name => MathS.Var(name)).ToArray();
var solutions = MathS.SolveSystem(statement, unknowns);
Assert.NotNull(solutions);
Assert.Equal(rows, solutions.RowCount);

Check warning on line 517 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 517 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

Dereference of a possibly null reference.

Check warning on line 517 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

Dereference of a possibly null reference.
var equations = AngouriMath.Core.EquationSystem.EquationsOf(statement, out _);
Assert.NotNull(equations);
Assert.Equal(MathS.Equations(equations).Solve(unknowns), solutions);

Check warning on line 520 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

Possible null reference argument for parameter 'equations' in 'EquationSystem MathS.Equations(IEnumerable<Entity> equations)'.

Check warning on line 520 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

Possible null reference argument for parameter 'equations' in 'EquationSystem MathS.Equations(IEnumerable<Entity> equations)'.

Check warning on line 520 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

Possible null reference argument for parameter 'equations' in 'EquationSystem MathS.Equations(IEnumerable<Entity> equations)'.
for (var row = 0; row < solutions.RowCount; row++)
foreach (var equation in equations)
{
Expand All @@ -534,7 +534,7 @@
{
var solutions = MathS.SolveSystem("x + y = 3 and x - y = 1", "x", "y");
Assert.NotNull(solutions);
Assert.Equal(1, solutions.RowCount);

Check warning on line 537 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (ubuntu-latest)

Dereference of a possibly null reference.

Check warning on line 537 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (windows-latest)

Dereference of a possibly null reference.

Check warning on line 537 in Sources/Tests/UnitTests/Common/SolverRegressionTest.cs

View workflow job for this annotation

GitHub Actions / Test (macos-latest)

Dereference of a possibly null reference.
Assert.True(solutions[0, 0] == 2 && solutions[0, 1] == 1, solutions.ToString());
}

Expand Down Expand Up @@ -662,6 +662,47 @@
}
}

// Newton's method is run from every sign change its scan of the real line brackets, at points 0.2 apart. A root
// beside a pole, or beside a point the expression has no value at, has no sign change between it and the next
// point of the scan: tan(x) = 2x is -0.34 at 4.6 and -21 at 4.8, with its root at 4.6042 and the pole at 3pi/2
// between them, and gamma(x) = 1 has no value at -4 and its roots at -3.9553 and -3.1436 lie on either side
// of -3.8 and -3.2, both below 1. Those roots were not answered. The reference roots are mpmath's, to 20 digits,
// and each answer is the whole list of real roots in [-10, 10].
// https://github.com/asc-community/AngouriMath/issues/2545
[Theory]
[InlineData("tan(x) = 2 x", new[] { "-7.7898837511445727737", "-4.6042167772005765146", "-1.1655611852072113068", "0",
"1.1655611852072113068", "4.6042167772005765146", "7.7898837511445727737" })]
[InlineData("x tan(x) = 28", new[] { "-7.5892948990851493579", "-4.5512534613810153626", "-1.516681996667486146",
"1.516681996667486146", "4.5512534613810153626", "7.5892948990851493579" })]
public void Issue2545_ARootBesideAPoleIsAnswered(string equation, string[] expected)
{
var roots = Assert.IsType<Entity.Set.FiniteSet>(equation.ToEntity().Solve("x"));
AssertTheRealRootsInTheBox(roots.Select(root => Assert.IsAssignableFrom<Entity.Number.Complex>(root.Evaled)), expected);
}

// The issue's own example, which the solver now answers by its whole roots and a set builder (#2547), so it is
// asked of Newton's method by name. x! = x is the same equation for x other than 0, and both are answered alike.
// https://github.com/asc-community/AngouriMath/issues/2545
[Theory]
[InlineData("gamma(x) - 1")]
[InlineData("x! - x")]
public void Issue2545_GammaIsOneAtEveryRealRootInTheBox(string expression)
=> AssertTheRealRootsInTheBox(expression.ToEntity().SolveNt("x"), new[] {
"-9.9999997244266292", "-9.0000027557148227", "-7.9999751970958207", "-7.0001983334073248",
"-5.9986074800808756", "-5.0082181683225935", "-3.9552942848585979", "-3.1435808883499801", "1", "2" });

private static void AssertTheRealRootsInTheBox(System.Collections.Generic.IEnumerable<Entity.Number.Complex> roots, string[] expected)
{
var reals = roots.Where(root => root.ImaginaryPart.IsZero)
.Select(root => root.RealPart.EDecimal.ToDouble())
.Where(root => root >= -10 && root <= 10)
.OrderBy(root => root)
.ToList();
Assert.Equal(expected.Length, reals.Count);
foreach (var (value, root) in expected.Select(double.Parse).Zip(reals))
Assert.True(System.Math.Abs(value - root) <= 1e-12 * System.Math.Max(1, System.Math.Abs(value)), $"{root} for {value}");
}

private static readonly PeterO.Numbers.EContext Unfloored = new(100, PeterO.Numbers.ERounding.HalfUp, -100000, 100000, false);

// Real parts, evaluated without the exponent floor, of roots each checked to be real.
Expand Down
Loading