Skip to content

Commit 1f23e1c

Browse files
Rafael-SOWNetclaude
andcommitted
A value cached on a node is the value under the settings in force
Evaled, InnerSimplified, DomainCondition, a matrix's determinant, inverse, adjugate, rank, eigenvalues and echelon forms, and an interval's numeric ends were kept as first computed and answered under any settings after, on any thread; Evaled alone noted the precision. 1/3 - 0.33333333333333333333 evaluated inside a zero range of 1e-10 was 0 afterwards at the defaults, where it is 3.3E-21. Every setting's stack now lives in one immutable SettingsState.State, made once per path of scopes from the defaults, so the scopes the library opens on every call reach the same state each time and a balanced open and close puts back the very state it replaced. A setting reads its value from it; Snapshot and StillHolds become one reference comparison. A flow holds one Scope per scope open, with its own id, so a scope is released by its id alone: disposing twice, or a stale copy after the same scope reopened, does nothing, and a scope closed out of order replays the ones above it. States one scope away are held weakly, each keeping the one it was reached from, so scopes of values that differ on every call are collected once nothing is open or cached under them, and at most 32 entries of one setting are kept. The caches above are SettingsDependent<T>: a value computed at the defaults is held as it is, a value computed in a scope with its state, and the last two states are kept, so a node asked in turn under Solve's settings and its analytical solver's is not recomputed at every turn. Entity gets a copy constructor so that a `with` copy keeps the structural caches and not the values. TryDowncast now simplifies the root it does not replace outside the 1e-7 zero range it guesses a rational with. Kernel benchmark against master on one machine: allocation lower on Derivate (-4.1%), EvalPolynomialFresh (-3.5%), SimplifyEasy (-3.4%) and SimplifyHard (-5.1%), from the evaluation cache no longer allocating at the defaults; SolveEasy +9.0%, from the residual check evaluating its roots with downcasting off rather than reading values cached with it on. Part of #2479 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 64a7160 commit 1f23e1c

9 files changed

Lines changed: 648 additions & 178 deletions

File tree

‎BREAKING-CHANGES.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,6 +244,31 @@ complex constant, an argument of any other shape. With `Simplify`, against mpmat
244244
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
245245
`pi`, which is the value for `|Im y| < 1`.
246246

247+
### A value cached on a node is the value under the settings in force
248+
249+
**Silent: a stale value is corrected.** `Evaled`, `InnerSimplified`, `DomainCondition`, a matrix's `Determinant`,
250+
`Inverse`, `Adjugate`, `Rank`, `Eigenvalues` and row echelon forms, and the ends of an interval as `Contains` reads them,
251+
are computed once per node and kept. Each was kept whatever the settings were then, and answered under any settings
252+
afterwards, on any thread; only `Evaled` noted `DecimalPrecisionContext`. An evaluation rounds by the settings —
253+
`PrecisionErrorZeroRange` decides what is zero — so the same node answered differently depending on where it had first
254+
been asked ([#2479](https://github.com/asc-community/AngouriMath/issues/2479)). Each is now kept with the settings it
255+
was computed under and answered only under those. Asked of one node first inside `PrecisionErrorZeroRange.Set(1e-10)`,
256+
then at the defaults:
257+
258+
| Input | At the defaults, was (2.7.0) | Now |
259+
|---|---|---|
260+
| `(1/3 - 0.33333333333333333333).Evaled` | `0` | `3.333…E-21` |
261+
| `(1 + 1e-20).Evaled` | `1` | `1.00000000000000000001` |
262+
| `(x * (1/3 - 0.33333333333333333333)).InnerSimplified` | `0` | `x * (1/3 - 0.33333333333333333333)` |
263+
| `(1 / (x - (1/3 - 0.33333333333333333333))).DomainCondition` | `not x = 0` | `not x - (1/3 - 0.33333333333333333333) = 0` |
264+
| `[[0.333333333333333333333333, 1], [1, 3]].Determinant` | `0` | `0.333333333333333333333333 * 3 - 1` |
265+
| the same matrix's `Rank` | `1` | `2` |
266+
| the same matrix's `Inverse` | `null` | `[[-3000000000000000000000000, 1000000000000000000000000], [1000000000000000000000000, -333333333333333333333333]]` |
267+
| `[1/3 - 0.33333333333333333333; 1].Contains(0)` | `True` | `False` |
268+
269+
In the other order each value computed at the defaults came back inside the scope: `Evaled` of the first was
270+
`3.333…E-21` there, where the scope's answer is `0`. Outside any scope nothing moves.
271+
247272
### `dot` and `cross` of a name for a vector are nodes
248273

249274
**Not silent: what was refused now parses.** `dot(a, b)` and `cross(a, b)` threw `InvalidArgumentParseException`

‎Sources/AngouriMath/Convenience/SettingClass.cs‎

Lines changed: 339 additions & 122 deletions
Large diffs are not rendered by default.

‎Sources/AngouriMath/Core/Entity/Entity.Definition.cs‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,28 @@ public virtual bool Equals(Entity? other)
132132
/// <summary>The same for the hash: the node's kind, with each node's parts combined in by its own record.</summary>
133133
public override int GetHashCode() => EqualityContract.GetHashCode();
134134

135+
/// <summary>Makes a node, with every cache empty.</summary>
136+
protected Entity() { }
137+
138+
/// <summary>
139+
/// The copy a <c>with</c> makes -- <see cref="WithCodomain"/>, and a derivative taken once
140+
/// more -- which is another node: it keeps the caches of what it shares with
141+
/// <paramref name="original"/>, the children and what is counted from them, and not the
142+
/// values, which a codomain or an order of differentiation changes.
143+
/// https://github.com/asc-community/AngouriMath/issues/2479
144+
/// </summary>
145+
protected Entity(Entity original)
146+
{
147+
directChildren = original.directChildren;
148+
isFinite = original.isFinite;
149+
complexity = original.complexity;
150+
vars = original.vars;
151+
varsAndConsts = original.varsAndConsts;
152+
freeVariables = original.freeVariables;
153+
simplifiedRate = original.simplifiedRate;
154+
sortHashes = original.sortHashes;
155+
}
156+
135157
/// <summary>
136158
/// Returns the array of the direct children. Will be
137159
/// only called once, so no need to cache anything.

‎Sources/AngouriMath/Core/Entity/Omni/Entity.Matrix.cs‎

Lines changed: 14 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -318,7 +318,8 @@ public Entity AsScalar()
318318
},
319319
this
320320
);
321-
private LazyPropertyA<Entity?> determinant;
321+
// Computed by arithmetic on the entries, which the settings round: https://github.com/asc-community/AngouriMath/issues/2479
322+
private Convenience.SettingsDependent<Entity?> determinant;
322323

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

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

468471

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

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

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

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

728735
/// <summary>
729736
/// Returns a vector, where the i-th element

‎Sources/AngouriMath/Core/Entity/Omni/Entity.Omni.Classes.cs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -241,10 +241,11 @@ public sealed partial record Interval(Entity Left, bool LeftClosed, Entity Right
241241
/// </summary>
242242
public bool IsNumeric => !LeftReal.IsNaN && !RightReal.IsNaN;
243243

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

249250
private static bool IsALessThanB(Real A, Real B, bool closed)
250251
=> A < B || closed && A == B;

‎Sources/AngouriMath/Functions/Continuous/Solvers/EquationSolver/AnalyticalEquationSolver.cs‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -164,12 +164,20 @@ static Entity TryDowncast(Entity equation, Variable x, Entity root)
164164
{
165165
if (root.Evaled is not Complex preciseValue)
166166
return root;
167-
using var _ = MathS.Settings.FloatToRationalIterCount.Set(20);
168-
using var __ = MathS.Settings.PrecisionErrorZeroRange.Set(1e-7m);
169-
var downcasted = Complex.Create(preciseValue.RealPart, preciseValue.ImaginaryPart);
170-
if (equation.Substitute(x, downcasted).Evaled is not Complex error)
171-
return root;
172-
return IsGenuineRoot(error) && downcasted.RealPart is Rational && downcasted.ImaginaryPart is Rational
167+
Complex downcasted;
168+
bool genuine;
169+
using (MathS.Settings.FloatToRationalIterCount.Set(20))
170+
using (MathS.Settings.PrecisionErrorZeroRange.Set(1e-7m))
171+
{
172+
downcasted = Complex.Create(preciseValue.RealPart, preciseValue.ImaginaryPart);
173+
if (equation.Substitute(x, downcasted).Evaled is not Complex error)
174+
return root;
175+
genuine = IsGenuineRoot(error);
176+
}
177+
// The root the guess is not, simplified under the solver's own settings rather than
178+
// the loose tolerance the guess is made with, which would round it.
179+
// https://github.com/asc-community/AngouriMath/issues/2479
180+
return genuine && downcasted.RealPart is Rational && downcasted.ImaginaryPart is Rational
173181
? downcasted : root.InnerSimplified;
174182
}
175183

‎Sources/AngouriMath/Functions/Evaluation/Evaluation.Definition.cs‎

Lines changed: 17 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,9 @@ partial record Entity
5050
(Boolean(true), var r) => r,
5151
(var l, var r) => l & r,
5252
}))), this).InnerSimplified;
53-
private LazyPropertyA<Entity> domainCondition;
53+
// What a condition simplifies to depends on the settings, as any evaluation does.
54+
// https://github.com/asc-community/AngouriMath/issues/2479
55+
private Convenience.SettingsDependent<Entity> domainCondition;
5456

5557
/// <summary>
5658
/// Where a piecewise is defined: where some case's predicate holds, no earlier one does,
@@ -482,47 +484,19 @@ public Entity Evaled
482484
// WithCodomain may evaluate to NaN, and still goes through it.
483485
if (this is Number && (Codomain == DefaultCodomain || Codomain == Domain.Any))
484486
return this;
485-
// Cached with the precision it was computed at, and read back only at that
486-
// precision: a hundred digits of pi are the wrong answer at five hundred. The
487-
// stamp is the precision setting's frame for this flow, compared by reference.
488-
// Frames are immutable, a scope opened and closed in order restores the very
489-
// frame that was under it, and a flow outside every scope has none. It was a
490-
// count of precision changes for the whole process, which could not tell one
491-
// flow's scope from another's, so a flow at a hundred digits read pi at three
492-
// hundred while another flow's scope was open.
493-
// https://github.com/asc-community/AngouriMath/issues/1505
494-
// The frame is read before the computation, so a scope opened and closed inside
495-
// it leaves the value stamped with the frame it was asked in.
496-
// https://github.com/asc-community/AngouriMath/issues/1367
497-
// And stamped with its owner: a record's `with` -- WithCodomain, and the
498-
// derivative's rewrites -- copies every field, this one included, and a value
499-
// computed for the original is not the copy's.
500-
// The value and its stamps are one object, published in one store, so that no
501-
// flow reads one flow's value under another's stamp.
502-
// Until a precision scope has been opened somewhere, no flow has a frame, and a
503-
// cached value is read without asking for one: the flow's frame is an async-local
504-
// read, several times the cost of the rest of this path.
505-
var precisionSetting = MathS.Settings.DecimalPrecisionContext;
506-
var precision = precisionSetting.EverScoped ? ((Convenience.ISettingState)precisionSetting).CurrentState : null;
507-
if (System.Threading.Volatile.Read(ref evaled) is { } cached
508-
&& ReferenceEquals(cached.Owner, this) && ReferenceEquals(cached.Precision, precision))
509-
return cached.Value;
510-
var computed = InnerSimplifyWithCheck(false);
511-
System.Threading.Volatile.Write(ref evaled, new EvaledValue(computed, this, precision));
512-
return computed;
487+
// Cached with the settings it was computed under, and read back only under those: a
488+
// hundred digits of pi are the wrong answer at five hundred
489+
// (https://github.com/asc-community/AngouriMath/issues/1505), and 1/3 -
490+
// 0.33333333333333333333 is 0 with the zero range at 1e-10 and 3.3E-21 at the
491+
// default (https://github.com/asc-community/AngouriMath/issues/2479). The state is
492+
// taken before the computation, so a scope opened and closed inside it leaves the
493+
// value stamped with the state it was asked in
494+
// (https://github.com/asc-community/AngouriMath/issues/1367); a `with` copy does not
495+
// carry it, which the copy constructor sees to.
496+
return evaled.TryGetValue(out var value) ? value : evaled.Computed(static @this => @this.InnerSimplifyWithCheck(false), this);
513497
}
514498
}
515-
516-
/// <summary>A value of <see cref="Evaled"/>, with the node and the precision it was computed for.</summary>
517-
private sealed class EvaledValue
518-
{
519-
internal readonly Entity Value;
520-
internal readonly Entity Owner;
521-
internal readonly object? Precision;
522-
internal EvaledValue(Entity value, Entity owner, object? precision)
523-
=> (Value, Owner, Precision) = (value, owner, precision);
524-
}
525-
private EvaledValue? evaled;
499+
private Convenience.SettingsDependent<Entity> evaled;
526500

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

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

0 commit comments

Comments
 (0)