2026-11-05 10:39:40 +01:00
|
|
|
using AngouriMath;
|
|
|
|
|
|
|
|
|
|
using PeterO.Numbers;
|
|
|
|
|
|
|
|
|
|
namespace AIStudio.Tools.Mathematics;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Checks numerically whether two expressions are equal, at fixed sample points.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <remarks>
|
|
|
|
|
/// A symbolic answer is only as good as the library which gave it, and AngouriMath changes answers
|
|
|
|
|
/// between releases. The tools therefore check what they can: a simplification against its input, an
|
|
|
|
|
/// antiderivative by its derivative, a solution by inserting it.<br/><br/>
|
|
|
|
|
/// The sample points are exact rationals between 0.6 and 2.3, so a polynomial is evaluated exactly,
|
|
|
|
|
/// however much its terms cancel, and everything else at 50 digits. They are fixed, so the same
|
|
|
|
|
/// question gets the same answer every time; the providers cache a conversation from its beginning.
|
|
|
|
|
/// A point where either side has no value, such as a pole, is skipped. Agreement at the points
|
|
|
|
|
/// supports the equality; it does not prove it.<br/><br/>
|
|
|
|
|
/// A derivative is compared with the central difference of its function, over a step of 1e-20 at 60
|
2026-11-25 18:45:24 +01:00
|
|
|
/// digits. The index of a family of solutions takes three integers of its set instead, -1, 0, and 1 for
|
|
|
|
|
/// any integer, since such a solution holds for those values only.<br/><br/>
|
2026-11-05 10:39:40 +01:00
|
|
|
/// Call it inside a computation of MathComputationService.
|
|
|
|
|
/// </remarks>
|
|
|
|
|
public static class NumericCheck
|
|
|
|
|
{
|
|
|
|
|
private const int SAMPLE_POINTS = 6;
|
|
|
|
|
|
|
|
|
|
private const int MIN_VALID_POINTS = 3;
|
|
|
|
|
|
|
|
|
|
private const int PRECISION = 50;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The values the variables take, in hundredths: irregular, so that no point lies on a pattern
|
|
|
|
|
/// such as a multiple of pi, and eleven of them, a prime, so that the variables of a point differ.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static readonly int[] SAMPLE_HUNDREDTHS = [61, 73, 89, 107, 119, 131, 147, 163, 179, 197, 223];
|
|
|
|
|
|
|
|
|
|
private static readonly EDecimal TOLERANCE = EDecimal.FromString("1e-30");
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The precision of a derivative check: the central difference divides by its tiny step.
|
|
|
|
|
/// </summary>
|
2026-11-25 18:45:24 +01:00
|
|
|
/// <remarks>
|
|
|
|
|
/// It suffices for a function no larger than its derivative, with 20 digits to spare. The difference
|
|
|
|
|
/// of a larger one, such as 100! + sin(x) or gamma(100, x), would be lost in the rounding of its
|
|
|
|
|
/// values, so the check takes one digit more for each power of ten by which the function exceeds its
|
|
|
|
|
/// derivative, see DerivativePrecisionAt.
|
|
|
|
|
/// </remarks>
|
2026-11-05 10:39:40 +01:00
|
|
|
private const int DERIVATIVE_PRECISION = 60;
|
|
|
|
|
|
2026-11-25 18:45:24 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// The highest precision of a derivative check; a point which would need more is left out.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private const int MAX_DERIVATIVE_PRECISION = 1_000;
|
|
|
|
|
|
2026-11-05 10:39:40 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// The step of the central difference: rounding at 60 digits costs about 1e-40 of it, and its own
|
|
|
|
|
/// error, about the square of the step, 1e-40 as well.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static readonly Entity.Number.Rational DERIVATIVE_STEP = Entity.Number.Rational.Create(EInteger.One, EInteger.FromInt32(10).Pow(20));
|
|
|
|
|
|
|
|
|
|
private static readonly Entity.Number.Rational TWO_DERIVATIVE_STEPS = Entity.Number.Rational.Create(EInteger.FromInt32(2), EInteger.FromInt32(10).Pow(20));
|
|
|
|
|
|
|
|
|
|
private static readonly EDecimal DERIVATIVE_TOLERANCE = EDecimal.FromString("1e-20");
|
|
|
|
|
|
2026-11-25 18:45:24 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// The integers an index of a family of solutions may take, in the order they are tried.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static readonly int[] INDEX_CANDIDATES = [-1, 0, 1, 2, -2, 3, -3];
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// How many integers of its set an index takes across the sample points.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private const int INDEX_VALUES = 3;
|
|
|
|
|
|
2026-11-05 10:39:40 +01:00
|
|
|
/// <summary>
|
|
|
|
|
/// Checks whether two expressions agree at every sample point where both have a value.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <remarks>
|
|
|
|
|
/// A condition of AngouriMath, as in x + 1 provided not x - 1 = 0, is left aside on both sides:
|
|
|
|
|
/// the expressions are compared where they have a value.
|
|
|
|
|
/// </remarks>
|
|
|
|
|
/// <param name="left">One expression.</param>
|
|
|
|
|
/// <param name="right">The other expression.</param>
|
|
|
|
|
/// <returns>What the check found.</returns>
|
2026-11-25 18:45:24 +01:00
|
|
|
public static NumericCheckOutcome AreEqual(Entity left, Entity right) => AreEqual(left, right, []);
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Checks whether two expressions agree at every sample point where both have a value, with the indices of a
|
|
|
|
|
/// family of solutions taking integers of their sets.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="left">One expression.</param>
|
|
|
|
|
/// <param name="right">The other expression.</param>
|
|
|
|
|
/// <param name="indices">The indices which occur freely in the expressions, e.g., n for any integer.</param>
|
|
|
|
|
/// <returns>What the check found; not possible when an index takes none of the integers tried.</returns>
|
|
|
|
|
public static NumericCheckOutcome AreEqual(Entity left, Entity right, IReadOnlyList<SolutionIndex> indices)
|
2026-11-05 10:39:40 +01:00
|
|
|
{
|
|
|
|
|
left = WithoutCondition(left);
|
|
|
|
|
right = WithoutCondition(right);
|
|
|
|
|
var variables = MathVariables.FreeIn(left).Concat(MathVariables.FreeIn(right)).Distinct().OrderBy(variable => variable.Name, StringComparer.Ordinal).ToArray();
|
2026-11-25 18:45:24 +01:00
|
|
|
var indexValues = IndexValues(indices);
|
|
|
|
|
if (indexValues.Values.Any(values => values.Count == 0))
|
|
|
|
|
return NumericCheckOutcome.NOT_POSSIBLE;
|
2026-11-05 10:39:40 +01:00
|
|
|
|
|
|
|
|
using var precision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(PRECISION));
|
|
|
|
|
var validPoints = 0;
|
|
|
|
|
for (var point = 0; point < SAMPLE_POINTS; point++)
|
|
|
|
|
{
|
2026-11-25 18:45:24 +01:00
|
|
|
var assignment = SampleAssignment(point, variables, indexValues);
|
2026-11-05 10:39:40 +01:00
|
|
|
var leftValue = ValueAt(left, assignment);
|
|
|
|
|
var rightValue = ValueAt(right, assignment);
|
|
|
|
|
if (leftValue is null || rightValue is null)
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
validPoints++;
|
|
|
|
|
if (!AreClose(leftValue, rightValue, TOLERANCE))
|
|
|
|
|
return NumericCheckOutcome.FAILED;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return validPoints >= MIN_VALID_POINTS ? NumericCheckOutcome.PASSED : NumericCheckOutcome.NOT_POSSIBLE;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Checks whether one expression is the derivative of another, by a central difference at each sample point.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="derivative">The claimed derivative.</param>
|
|
|
|
|
/// <param name="function">The function.</param>
|
|
|
|
|
/// <param name="variable">The variable of the derivative.</param>
|
|
|
|
|
/// <returns>What the check found.</returns>
|
|
|
|
|
public static NumericCheckOutcome IsDerivativeOf(Entity derivative, Entity function, Entity.Variable variable)
|
|
|
|
|
{
|
|
|
|
|
derivative = WithoutCondition(derivative);
|
|
|
|
|
function = WithoutCondition(function);
|
|
|
|
|
var variables = MathVariables.FreeIn(derivative).Concat(MathVariables.FreeIn(function)).Append(variable).Distinct().OrderBy(free => free.Name, StringComparer.Ordinal).ToArray();
|
|
|
|
|
|
|
|
|
|
using var precision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(DERIVATIVE_PRECISION));
|
|
|
|
|
var validPoints = 0;
|
|
|
|
|
for (var point = 0; point < SAMPLE_POINTS; point++)
|
|
|
|
|
{
|
|
|
|
|
var assignment = SampleAssignment(point, variables);
|
|
|
|
|
var at = assignment[variable];
|
|
|
|
|
var claimed = ValueAt(derivative, assignment);
|
2026-11-25 18:45:24 +01:00
|
|
|
var value = ValueAt(function, assignment);
|
|
|
|
|
if (claimed is null || value is null)
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
var digits = DerivativePrecisionAt(value, claimed);
|
|
|
|
|
if (digits > MAX_DERIVATIVE_PRECISION)
|
|
|
|
|
continue;
|
|
|
|
|
|
|
|
|
|
using var pointPrecision = MathS.Settings.DecimalPrecisionContext.Set(EContext.ForPrecision(digits));
|
2026-11-05 10:39:40 +01:00
|
|
|
var above = ValueAt(function, With(assignment, variable, (at + DERIVATIVE_STEP).InnerSimplified));
|
|
|
|
|
var below = ValueAt(function, With(assignment, variable, (at - DERIVATIVE_STEP).InnerSimplified));
|
2026-11-25 18:45:24 +01:00
|
|
|
if (above is null || below is null)
|
2026-11-05 10:39:40 +01:00
|
|
|
continue;
|
|
|
|
|
|
2026-11-25 18:45:24 +01:00
|
|
|
var difference = NumericEvaluator.EvaluateAt(((Entity)above - below) / TWO_DERIVATIVE_STEPS, digits);
|
2026-11-05 10:39:40 +01:00
|
|
|
validPoints++;
|
|
|
|
|
if (!AreClose(claimed, difference, DERIVATIVE_TOLERANCE))
|
|
|
|
|
return NumericCheckOutcome.FAILED;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return validPoints >= MIN_VALID_POINTS ? NumericCheckOutcome.PASSED : NumericCheckOutcome.NOT_POSSIBLE;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2026-11-25 18:45:24 +01:00
|
|
|
/// The precision a central difference needs at a point: DERIVATIVE_PRECISION, and one digit more for each
|
|
|
|
|
/// power of ten by which the function exceeds its derivative.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <remarks>
|
|
|
|
|
/// Rounding to p digits changes each value of the function by about 10^-p of it, which the division by
|
|
|
|
|
/// the step of 1e-20 enlarges to 10^(20 - p) of it. To stay within DERIVATIVE_TOLERANCE of the derivative,
|
|
|
|
|
/// p has to exceed 40 plus the decimal logarithm of their ratio; DERIVATIVE_PRECISION keeps 20 digits
|
|
|
|
|
/// more. Against a derivative of 0, the tolerance is absolute.
|
|
|
|
|
/// </remarks>
|
|
|
|
|
private static int DerivativePrecisionAt(Entity.Number.Complex value, Entity.Number.Complex derivative)
|
|
|
|
|
{
|
|
|
|
|
var ratio = DecimalLogarithmOfSize(value) - (IsZero(derivative) ? 0 : DecimalLogarithmOfSize(derivative));
|
|
|
|
|
return DERIVATIVE_PRECISION + (int)Math.Max(0, Math.Ceiling(ratio));
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The decimal logarithm of the larger part of a number, roughly, also beyond the range of a double.
|
2026-11-05 10:39:40 +01:00
|
|
|
/// </summary>
|
2026-11-25 18:45:24 +01:00
|
|
|
private static double DecimalLogarithmOfSize(Entity.Number.Complex number)
|
|
|
|
|
{
|
|
|
|
|
var size = EDecimal.Max(number.RealPart.EDecimal.Abs(), number.ImaginaryPart.EDecimal.Abs());
|
|
|
|
|
if (size.IsZero)
|
|
|
|
|
return double.NegativeInfinity;
|
|
|
|
|
|
|
|
|
|
return size.Exponent.ToInt64Checked() + size.Mantissa.Abs().GetDigitCountAsInt64() - 1;
|
|
|
|
|
}
|
2026-11-05 10:39:40 +01:00
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The values of the variables at one sample point.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="point">The number of the point, from zero.</param>
|
|
|
|
|
/// <param name="variables">The variables, in a fixed order.</param>
|
|
|
|
|
/// <returns>Each variable with its exact value.</returns>
|
2026-11-25 18:45:24 +01:00
|
|
|
public static IReadOnlyDictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables) => SampleAssignment(point, variables, new Dictionary<Entity.Variable, IReadOnlyList<Entity>>());
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The values of the variables at one sample point, where the indices of a family of solutions take integers of their sets.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="point">The number of the point, from zero.</param>
|
|
|
|
|
/// <param name="variables">The variables, in a fixed order.</param>
|
|
|
|
|
/// <param name="indices">The indices among the variables.</param>
|
|
|
|
|
/// <returns>Each variable with its exact value; an index which takes none of the integers tried is left out.</returns>
|
|
|
|
|
public static IReadOnlyDictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables, IReadOnlyList<SolutionIndex> indices) => SampleAssignment(point, variables, IndexValues(indices));
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The integers each index takes, at most INDEX_VALUES of them.
|
|
|
|
|
/// </summary>
|
|
|
|
|
private static Dictionary<Entity.Variable, IReadOnlyList<Entity>> IndexValues(IReadOnlyList<SolutionIndex> indices)
|
|
|
|
|
{
|
|
|
|
|
var values = new Dictionary<Entity.Variable, IReadOnlyList<Entity>>(indices.Count);
|
|
|
|
|
foreach (var index in indices)
|
|
|
|
|
values[index.Variable] = [..INDEX_CANDIDATES.Where(index.Takes).Take(INDEX_VALUES).Select(Entity (candidate) => Entity.Number.Integer.Create(candidate))];
|
|
|
|
|
|
|
|
|
|
return values;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static Dictionary<Entity.Variable, Entity> SampleAssignment(int point, IReadOnlyList<Entity.Variable> variables, IReadOnlyDictionary<Entity.Variable, IReadOnlyList<Entity>> indexValues)
|
2026-11-05 10:39:40 +01:00
|
|
|
{
|
|
|
|
|
var assignment = new Dictionary<Entity.Variable, Entity>(variables.Count);
|
|
|
|
|
for (var index = 0; index < variables.Count; index++)
|
|
|
|
|
{
|
2026-11-25 18:45:24 +01:00
|
|
|
// An index takes integers of its set, since a family of solutions holds only there:
|
|
|
|
|
if (indexValues.TryGetValue(variables[index], out var values))
|
2026-11-05 10:39:40 +01:00
|
|
|
{
|
2026-11-25 18:45:24 +01:00
|
|
|
if (values.Count > 0)
|
|
|
|
|
assignment[variables[index]] = values[(point + index) % values.Count];
|
|
|
|
|
|
2026-11-05 10:39:40 +01:00
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
var hundredths = SAMPLE_HUNDREDTHS[(point * 3 + index * 5) % SAMPLE_HUNDREDTHS.Length];
|
|
|
|
|
assignment[variables[index]] = Entity.Number.Rational.Create(hundredths, 100);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return assignment;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static Dictionary<Entity.Variable, Entity> With(IReadOnlyDictionary<Entity.Variable, Entity> assignment, Entity.Variable variable, Entity value) => new(assignment) { [variable] = value };
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// The value of an expression with its variables replaced, or null when it has none there.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="expression">The expression.</param>
|
|
|
|
|
/// <param name="assignment">The value of each variable.</param>
|
2026-11-25 18:45:24 +01:00
|
|
|
/// <returns>The value, or null for no value, an infinite one, one MathGuards.CheckValueAtPoint refuses, or one AngouriMath cannot evaluate.</returns>
|
2026-11-05 10:39:40 +01:00
|
|
|
public static Entity.Number.Complex? ValueAt(Entity expression, IReadOnlyDictionary<Entity.Variable, Entity> assignment)
|
|
|
|
|
{
|
|
|
|
|
try
|
|
|
|
|
{
|
|
|
|
|
var substituted = expression;
|
|
|
|
|
foreach (var (variable, value) in assignment)
|
|
|
|
|
substituted = substituted.Substitute(variable, value);
|
|
|
|
|
|
2026-11-25 18:45:24 +01:00
|
|
|
// A value of a variable may make a factorial or a power too large to be computed exactly, as x = 2.23 in
|
|
|
|
|
// (10^6 * x)!, or take a special function beyond its limits, as in gamma(1/2, 1000 * x). The check comes
|
|
|
|
|
// first, since EvaluableNumerical already computes the exact value:
|
|
|
|
|
MathGuards.CheckValueAtPoint(substituted);
|
2026-11-05 10:39:40 +01:00
|
|
|
if (!substituted.EvaluableNumerical)
|
|
|
|
|
return null;
|
|
|
|
|
|
|
|
|
|
//
|
|
|
|
|
// A polynomial at a sample point stays exact. Anything else is evaluated without the downcasting which turns
|
2026-11-25 18:45:24 +01:00
|
|
|
// tiny values into 0, and so is an exact 0: simplifying takes a value below about 1e-1000 for 0, and up to
|
|
|
|
|
// version 2.6.0, it took a tiny value such as 6.62607015e-34 * sin(0.61) for 0 at this precision, see
|
|
|
|
|
// AngouriMathBehaviorTests:
|
2026-11-05 10:39:40 +01:00
|
|
|
//
|
|
|
|
|
var exact = NumericEvaluator.ExactValueOf(substituted);
|
|
|
|
|
var number = exact is not null && !IsZero(exact) ? exact : NumericEvaluator.EvaluateAt(substituted, MathS.Settings.DecimalPrecisionContext.Value.Precision.ToInt32Checked());
|
|
|
|
|
return IsFinite(number) ? number : null;
|
|
|
|
|
}
|
|
|
|
|
catch (Exception exception) when (exception is not OperationCanceledException)
|
|
|
|
|
{
|
|
|
|
|
return null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
private static Entity WithoutCondition(Entity expression) => expression is Entity.Providedf provided ? provided.Expression : expression;
|
|
|
|
|
|
|
|
|
|
private static bool IsFinite(Entity.Number.Complex number) => IsFinite(number.RealPart.EDecimal) && IsFinite(number.ImaginaryPart.EDecimal);
|
|
|
|
|
|
|
|
|
|
private static bool IsZero(Entity.Number.Complex number) => number.RealPart.EDecimal.IsZero && number.ImaginaryPart.EDecimal.IsZero;
|
|
|
|
|
|
|
|
|
|
private static bool IsFinite(EDecimal value) => !value.IsNaN() && !value.IsInfinity();
|
|
|
|
|
|
|
|
|
|
private static bool AreClose(Entity.Number.Complex left, Entity.Number.Complex right, EDecimal tolerance)
|
|
|
|
|
{
|
|
|
|
|
var context = EContext.ForPrecision(PRECISION);
|
|
|
|
|
var difference = left.RealPart.EDecimal.Subtract(right.RealPart.EDecimal, context).Abs().Add(left.ImaginaryPart.EDecimal.Subtract(right.ImaginaryPart.EDecimal, context).Abs(), context);
|
|
|
|
|
var leftSize = left.RealPart.EDecimal.Abs().Add(left.ImaginaryPart.EDecimal.Abs(), context);
|
|
|
|
|
var rightSize = right.RealPart.EDecimal.Abs().Add(right.ImaginaryPart.EDecimal.Abs(), context);
|
|
|
|
|
|
|
|
|
|
//
|
|
|
|
|
// Against 0, the tolerance is absolute: an expression whose terms cancel, such as sin(2*x) - 2*sin(x)*cos(x),
|
|
|
|
|
// comes only as close as its rounding noise. Between two other values, it is relative, so that tiny values,
|
|
|
|
|
// such as those of a formula with the Planck constant, are still told apart:
|
|
|
|
|
//
|
|
|
|
|
var scale = leftSize.IsZero || rightSize.IsZero ? EDecimal.One : EDecimal.Max(leftSize, rightSize);
|
|
|
|
|
return difference.CompareTo(tolerance.Multiply(scale, context)) <= 0;
|
|
|
|
|
}
|
|
|
|
|
}
|