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 @@ -244,6 +244,31 @@ complex constant, an argument of any other shape. With `Simplify`, against mpmat
A symbol is read as real here, as everywhere the breaks are read, so `integral(1/(1+(t-y)^2), t, -oo, +oo)` is still
`pi`, which is the value for `|Im y| < 1`.

### A value cached on a node is the value under the settings in force

**Silent: a stale value is corrected.** `Evaled`, `InnerSimplified`, `DomainCondition`, a matrix's `Determinant`,
`Inverse`, `Adjugate`, `Rank`, `Eigenvalues` and row echelon forms, and the ends of an interval as `Contains` reads them,
are computed once per node and kept. Each was kept whatever the settings were then, and answered under any settings
afterwards, on any thread; only `Evaled` noted `DecimalPrecisionContext`. An evaluation rounds by the settings —
`PrecisionErrorZeroRange` decides what is zero — so the same node answered differently depending on where it had first
been asked ([#2479](https://github.com/asc-community/AngouriMath/issues/2479)). Each is now kept with the settings it
was computed under and answered only under those. Asked of one node first inside `PrecisionErrorZeroRange.Set(1e-10)`,
then at the defaults:

| Input | At the defaults, was (2.7.0) | Now |
|---|---|---|
| `(1/3 - 0.33333333333333333333).Evaled` | `0` | `3.333…E-21` |
| `(1 + 1e-20).Evaled` | `1` | `1.00000000000000000001` |
| `(x * (1/3 - 0.33333333333333333333)).InnerSimplified` | `0` | `x * (1/3 - 0.33333333333333333333)` |
| `(1 / (x - (1/3 - 0.33333333333333333333))).DomainCondition` | `not x = 0` | `not x - (1/3 - 0.33333333333333333333) = 0` |
| `[[0.333333333333333333333333, 1], [1, 3]].Determinant` | `0` | `0.333333333333333333333333 * 3 - 1` |
| the same matrix's `Rank` | `1` | `2` |
| the same matrix's `Inverse` | `null` | `[[-3000000000000000000000000, 1000000000000000000000000], [1000000000000000000000000, -333333333333333333333333]]` |
| `[1/3 - 0.33333333333333333333; 1].Contains(0)` | `True` | `False` |

In the other order each value computed at the defaults came back inside the scope: `Evaled` of the first was
`3.333…E-21` there, where the scope's answer is `0`. Outside any scope nothing moves.

### `dot` and `cross` of a name for a vector are nodes

**Not silent: what was refused now parses.** `dot(a, b)` and `cross(a, b)` threw `InvalidArgumentParseException`
Expand Down
461 changes: 339 additions & 122 deletions Sources/AngouriMath/Convenience/SettingClass.cs

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions Sources/AngouriMath/Core/Entity/Entity.Definition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,28 @@ public virtual bool Equals(Entity? other)
/// <summary>The same for the hash: the node's kind, with each node's parts combined in by its own record.</summary>
public override int GetHashCode() => EqualityContract.GetHashCode();

/// <summary>Makes a node, with every cache empty.</summary>
protected Entity() { }

/// <summary>
/// The copy a <c>with</c> makes -- <see cref="WithCodomain"/>, and a derivative taken once
/// more -- which is another node: it keeps the caches of what it shares with
/// <paramref name="original"/>, the children and what is counted from them, and not the
/// values, which a codomain or an order of differentiation changes.
/// https://github.com/asc-community/AngouriMath/issues/2479
/// </summary>
protected Entity(Entity original)
{
directChildren = original.directChildren;
isFinite = original.isFinite;
complexity = original.complexity;
vars = original.vars;
varsAndConsts = original.varsAndConsts;
freeVariables = original.freeVariables;
simplifiedRate = original.simplifiedRate;
sortHashes = original.sortHashes;
}

/// <summary>
/// Returns the array of the direct children. Will be
/// only called once, so no need to cache anything.
Expand Down
21 changes: 14 additions & 7 deletions Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs
Original file line number Diff line number Diff line change
Expand Up @@ -318,7 +318,8 @@ public Entity AsScalar()
},
this
);
private LazyPropertyA<Entity?> determinant;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Entity?> determinant;

/// <summary>
/// The determinant of the rows from <paramref name="row"/> down and the given
Expand Down Expand Up @@ -440,7 +441,8 @@ private static Entity Laplace(Matrix matrix, int row, int[] columns)
var lambda = Variable.CreateUnique(@this, "lambda");
return @this.CharacteristicPolynomial(lambda) is { } polynomial ? polynomial.SolveEquation(lambda) : null;
}, this);
private LazyPropertyA<Set?> eigenvalues;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Set?> eigenvalues;

/// <summary>Returns an inverse matrix if it exists</summary>
/// <remarks>
Expand All @@ -463,7 +465,8 @@ private static Entity Laplace(Matrix matrix, int row, int[] columns)
return OfTheShapeOf(@this, MathS.Matrix(@this.RowCount, @this.ColumnCount,
(row, column) => adjugate[row, column] / determinant).InnerSimplified);
}, this);
private LazyPropertyA<Matrix?> inverse;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Matrix?> inverse;


/// <summary>
Expand Down Expand Up @@ -600,7 +603,8 @@ public IEnumerator<Entity> GetEnumerator()
@ref.GetValue(static @this =>
OfTheShapeOf(@this, MathS.Matrix(Eliminate(@this, reduced: false).Entries).InnerSimplified),
this);
private LazyPropertyA<Matrix> @ref;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Matrix> @ref;

/// <summary>
/// Reduced row echelon form via Gaussian elimination.
Expand All @@ -613,7 +617,8 @@ public IEnumerator<Entity> GetEnumerator()
rref.GetValue(static @this =>
OfTheShapeOf(@this, MathS.Matrix(Eliminate(@this, reduced: true).Entries).InnerSimplified),
this);
private LazyPropertyA<Matrix> rref;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Matrix> rref;

/// <summary>
/// The number of linearly independent rows: of the elimination's pivots. For a symbolic matrix it is the
Expand All @@ -622,7 +627,8 @@ public IEnumerator<Entity> GetEnumerator()
/// </summary>
public int Rank =>
rank.GetValue(static @this => Eliminate(@this, reduced: false).Pivots, this);
private LazyPropertyA<int> rank;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<int> rank;

/// <summary>
/// Gaussian elimination over the entries, to the row echelon form, or with <paramref name="reduced"/> to the
Expand Down Expand Up @@ -723,7 +729,8 @@ private static bool IsZeroEntry(Entity entry)
return ToMatrix(Functions.GenTensorGuard.Adjoint(@this.InnerMatrix));
},
this);
private LazyPropertyA<Matrix?> adjugate;
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Matrix?> adjugate;

/// <summary>
/// Returns a vector, where the i-th element
Expand Down
5 changes: 3 additions & 2 deletions Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs
Original file line number Diff line number Diff line change
Expand Up @@ -241,10 +241,11 @@ public sealed partial record Interval(Entity Left, bool LeftClosed, Entity Right
/// </summary>
public bool IsNumeric => !LeftReal.IsNaN && !RightReal.IsNaN;

// Each end's value is an evaluation, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
private Real LeftReal => fLeft.GetValue(static @this => @this.Left.EvaluableNumerical && @this.Left.Evaled is Real re ? re : Real.NaN, this);
private LazyPropertyA<Real> fLeft;
private Convenience.SettingsDependent<Real> fLeft;
private Real RightReal => fRight.GetValue(static @this => @this.Right.EvaluableNumerical && @this.Right.Evaled is Real re ? re : Real.NaN, this);
private LazyPropertyA<Real> fRight;
private Convenience.SettingsDependent<Real> fRight;

private static bool IsALessThanB(Real A, Real B, bool closed)
=> A < B || closed && A == B;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -164,12 +164,20 @@ static Entity TryDowncast(Entity equation, Variable x, Entity root)
{
if (root.Evaled is not Complex preciseValue)
return root;
using var _ = MathS.Settings.FloatToRationalIterCount.Set(20);
using var __ = MathS.Settings.PrecisionErrorZeroRange.Set(1e-7m);
var downcasted = Complex.Create(preciseValue.RealPart, preciseValue.ImaginaryPart);
if (equation.Substitute(x, downcasted).Evaled is not Complex error)
return root;
return IsGenuineRoot(error) && downcasted.RealPart is Rational && downcasted.ImaginaryPart is Rational
Complex downcasted;
bool genuine;
using (MathS.Settings.FloatToRationalIterCount.Set(20))
using (MathS.Settings.PrecisionErrorZeroRange.Set(1e-7m))
{
downcasted = Complex.Create(preciseValue.RealPart, preciseValue.ImaginaryPart);
if (equation.Substitute(x, downcasted).Evaled is not Complex error)
return root;
genuine = IsGenuineRoot(error);
}
// The root the guess is not, simplified under the solver's own settings rather than
// the loose tolerance the guess is made with, which would round it.
// https://github.com/asc-community/AngouriMath/issues/2479
return genuine && downcasted.RealPart is Rational && downcasted.ImaginaryPart is Rational
? downcasted : root.InnerSimplified;
}

Expand Down
58 changes: 17 additions & 41 deletions Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,9 @@ partial record Entity
(Boolean(true), var r) => r,
(var l, var r) => l & r,
}))), this).InnerSimplified;
private LazyPropertyA<Entity> domainCondition;
// What a condition simplifies to depends on the settings, as any evaluation does.
// https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Entity> domainCondition;

/// <summary>
/// Where a piecewise is defined: where some case's predicate holds, no earlier one does,
Expand Down Expand Up @@ -482,47 +484,19 @@ public Entity Evaled
// WithCodomain may evaluate to NaN, and still goes through it.
if (this is Number && (Codomain == DefaultCodomain || Codomain == Domain.Any))
return this;
// Cached with the precision it was computed at, and read back only at that
// precision: a hundred digits of pi are the wrong answer at five hundred. The
// stamp is the precision setting's frame for this flow, compared by reference.
// Frames are immutable, a scope opened and closed in order restores the very
// frame that was under it, and a flow outside every scope has none. It was a
// count of precision changes for the whole process, which could not tell one
// flow's scope from another's, so a flow at a hundred digits read pi at three
// hundred while another flow's scope was open.
// https://github.com/asc-community/AngouriMath/issues/1505
// The frame is read before the computation, so a scope opened and closed inside
// it leaves the value stamped with the frame it was asked in.
// https://github.com/asc-community/AngouriMath/issues/1367
// And stamped with its owner: a record's `with` -- WithCodomain, and the
// derivative's rewrites -- copies every field, this one included, and a value
// computed for the original is not the copy's.
// The value and its stamps are one object, published in one store, so that no
// flow reads one flow's value under another's stamp.
// Until a precision scope has been opened somewhere, no flow has a frame, and a
// cached value is read without asking for one: the flow's frame is an async-local
// read, several times the cost of the rest of this path.
var precisionSetting = MathS.Settings.DecimalPrecisionContext;
var precision = precisionSetting.EverScoped ? ((Convenience.ISettingState)precisionSetting).CurrentState : null;
if (System.Threading.Volatile.Read(ref evaled) is { } cached
&& ReferenceEquals(cached.Owner, this) && ReferenceEquals(cached.Precision, precision))
return cached.Value;
var computed = InnerSimplifyWithCheck(false);
System.Threading.Volatile.Write(ref evaled, new EvaledValue(computed, this, precision));
return computed;
// Cached with the settings it was computed under, and read back only under those: a
// hundred digits of pi are the wrong answer at five hundred
// (https://github.com/asc-community/AngouriMath/issues/1505), and 1/3 -
// 0.33333333333333333333 is 0 with the zero range at 1e-10 and 3.3E-21 at the
// default (https://github.com/asc-community/AngouriMath/issues/2479). The state is
// taken before the computation, so a scope opened and closed inside it leaves the
// value stamped with the state it was asked in
// (https://github.com/asc-community/AngouriMath/issues/1367); a `with` copy does not
// carry it, which the copy constructor sees to.
return evaled.TryGetValue(out var value) ? value : evaled.Computed(static @this => @this.InnerSimplifyWithCheck(false), this);
}
}

/// <summary>A value of <see cref="Evaled"/>, with the node and the precision it was computed for.</summary>
private sealed class EvaledValue
{
internal readonly Entity Value;
internal readonly Entity Owner;
internal readonly object? Precision;
internal EvaledValue(Entity value, Entity owner, object? precision)
=> (Value, Owner, Precision) = (value, owner, precision);
}
private EvaledValue? evaled;
private Convenience.SettingsDependent<Entity> evaled;

/// <summary>
/// This is the result of naive simplifications, but not creating imprecise <see cref="Real"/> values unlike <see cref="Evaled"/>. In other
Expand Down Expand Up @@ -551,7 +525,9 @@ internal EvaledValue(Entity value, Entity owner, object? precision)
/// </code>
/// </example>
public Entity InnerSimplified => innerSimplified.GetValue(static @this => @this.InnerSimplifyWithCheck(true), this);
private LazyPropertyA<Entity> innerSimplified;
// Numbers are rounded as they are combined, by the settings in force: see Evaled.
// https://github.com/asc-community/AngouriMath/issues/2479
private Convenience.SettingsDependent<Entity> innerSimplified;

/// <summary>
/// Expands an equation trying to eliminate all the parentheses ( e. g. 2 * (x + 3) = 2 * x + 2 * 3 )
Expand Down
Loading
Loading