Repository navigation
Cheaper number creation: no search for a double that is provably no small rational, a Real without a downcasting scope, Evaled without a cache - #2457
Merged
Conversation
(Entity)double, (Entity)float, (Entity)Complex and the other conversions from a machine number read the decimal's mantissa into a double-double for the downcasting's pre-check, and that reading was over half of what the conversion cost. A double is m / 2^k already, so its continued fraction is Euclid's algorithm on two machine integers. The new check runs it exactly and returns Real only where it proves that neither the rounding onto an integer nor the continued-fraction search can return anything else: - the integer branch, from the distance to the nearest integer, with a factor of two to spare; - the search: any ratio p/q it returns, q <= MaxAbsNumeratorOrDenominatorValue, is within K (a_n t (1 + u) + N u q^2) / q^2 of x, under 1/(2 q^2), so it is a convergent of x by Legendre's theorem, and a convergent is only that close when the complete quotient after it is near 1/(A t). Each one is tested. The bound and its derivation are in the remarks on Real.IsProvablyNoSmallRational. Settings the bound does not cover (fewer than 30 digits, bits, traps, no rounding, a narrow exponent range, a bound past 10^9, tolerance times bound past 10^-3, more than 100 levels) go through the search as before, as does every value the check does not decide. Nothing else changes. Equivalence: NumberCreationAsOf270 is the 2.7.0 code path copied verbatim (840075a; it agrees with that unchanged library on all of the cases below), and AMachineNumberIsMadeAsBeforeTest compares type, Equals, hash, ToString and the decimal through every entry point (Entity, Real, Number, Complex, MathS.Numbers.Create, System.Numerics.Complex): 1,000,000 random bit patterns; 1,000,000 (r - 1/2) 10^k, k in -30..30; every p/q with |p| <= q < 1000; 200,000 doubles within 4 ulps of ratios with denominators up to 2e8; 1-8 ulps either side of short decimals; 16 ulps around 2^53, 2^62, 2^63, long.MinValue/MaxValue, 1e8, 1e9, 1e15; values around 1e-16 and 1e-50 alone and added to 1, 7, 0.5 and 1e6; subnormals, +-0, NaN, +-Infinity; 600,000 floats; 300,000 complex numbers. The edge sets and 60,000 random values again under each of 20 settings: precision 30, 300, 150 (wide exponents), 29, 20, unlimited exponents, rounding Down, PrecisionErrorZeroRange 1e-16/1e-12/1e-30/1e-6, MaxAbsNumeratorOrDenominatorValue 1e3/1e9/1e12, FloatToRationalIterCount 1/3/100/200, downcasting off. All identical. 99%+ of random doubles take the cheap path at the defaults. Measured on net10.0 Release, GC.GetAllocatedBytesForCurrentThread, warmed up, 200,000 values each, best of five (before -> after): (Entity)double, random in +-0.5 1096 B 0.458 us -> 616 B 0.186 us (Entity)double, random in +-5e4 1117 B 0.627 us -> 616 B 0.152 us (Entity)double, random in +-5e6 2254 B 1.168 us -> 615 B 0.134 us (Entity)Complex(x, 0.5x) 3217 B 1.417 us -> 2227 B 0.511 us (Entity)double then Evaled 1157 B 0.632 us -> 656 B 0.180 us (Entity)float, random in +-5e4 39895 B 19.3 us -> unchanged A float in that range is a ratio with a denominator a power of two under the bound, which the search turns into a Rational, so it still takes the search; what remains of a double's cost is EDecimal.FromDouble (392 B) and the Real (224 B). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A caller that wanted a Real holding exactly a decimal had to open a MathS.Settings.DowncastingEnabled.Set(false) scope around Real.Create: an async-local frame, 112 bytes and most of the time, per number. The new Real.CreateWithoutDowncasting(EDecimal) is what Create answers inside that scope, with no scope. Additive: nothing existing changes; PublicApi.txt records the one new member. Named for what it does rather than Create(value, bool downcast), whose "true" would have read as forcing the downcasting while the setting is off, which Create does not do. Equivalence: ARealMadeWithoutDowncastingTest compares it with Create under a DowncastingEnabled(false) scope -- exact type Real, Equals, hash, ToString, the decimal itself (the same instance) -- on 60,000 values (random doubles at every scale, their roundings to integers, ratios written out to 100 digits, zero, signed zero, NaN, the infinities, trailing zeros) at the defaults, with the downcasting off, and at 30 and 300 digits, and checks the setting is left on. Its doc example runs in DocumentationExamplesRunTest. Measured as the first commit's numbers (net10.0 Release, allocated bytes per call, warmed up, best of five over 200,000 calls): DowncastingEnabled.Set(false) scope alone 112 B 0.063 us Real.Create(EDecimal) inside that scope 336 B 0.074 us Real.CreateWithoutDowncasting(EDecimal) 224 B 0.014 us Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Evaled of a number computed InnerSimplify -- the number -- checked it against the codomain, and cached the result in a 40-byte EvaledValue stamped with the precision frame. A number has no children, and its codomain, its own type's or Any, contains it whatever the precision: the set of each is a test of the type alone (SpecialSet.MayContain). So the answer was the number itself at every precision, scoped or not, and the cache held nothing else. Now it is returned directly. A number given another codomain by WithCodomain, which may evaluate to NaN, still goes through the computation and the cache. Equivalence: ANumberEvaluatesToItselfTest asserts that Evaled, EvaluableNumerical and EvalNumerical() of integers, rationals, reals (with and without downcasting, 0.1, 1e-200, pi and e evaluated), NaN, the infinities and complex numbers is the same instance, read first and again, at the defaults; at 5, 30, 100 and 300 digits with a nested scope inside each and after it; with the downcasting off; on 64 threads each at its own precision; and that a rational in ZZ, a complex number in RR and 0.1 in QQ are NaN while 5 in RR is itself. It passes unchanged on the parent commit too, which is the proof that the old answer was the same. Measured as the first commit's numbers (net10.0 Release, allocated bytes per call, warmed up, best of five over 200,000 calls): Integer.Create(long) then Evaled 488 B 0.063 us -> 448 B 0.049 us (Entity)double then Evaled 656 B 0.180 us -> 616 B 0.156 us (Entity)double then EvalNumerical() 656 B 0.201 us -> 616 B 0.157 us Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #2457 +/- ##
==========================================
+ Coverage 86.97% 86.98% +0.01%
==========================================
Files 319 320 +1
Lines 71063 71174 +111
Branches 20734 20759 +25
==========================================
+ Hits 61808 61912 +104
- Misses 4968 4971 +3
- Partials 4287 4291 +4
Flags with carried forward coverage won't be shown. Click here to find out more.
🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Three commits, one per change, meant to be merged as they are (rebase, not squash). No answer changes, so there is no
BREAKING-CHANGES.mdentry.Real.IsProvablyNoSmallRational(inMachineNumbers.cs) answers "Real" only where it proves the old code would return that sameReal: it bounds how far any ratio the old search could return can be from x, which by Legendre's theorem makes that ratio a convergent of x, and tests each convergent within the bound. The proof is in the method's remarks. Every other value, and every setting outside the proof (fewer than 30 digits, traps, a narrow exponent range, a numerator/denominator bound above 1e9, …), goes through the old path unchanged.Real.CreateWithoutDowncasting(EDecimal), a public, additive way to make aRealwithout aDowncastingEnabledscope. Named this way rather thanCreate(value, bool downcast), sincedowncast: truewould read as forcing downcasting while the setting is off, whichCreatedoes not do.Evaledis the number, without caching it, for a number with its own default codomain orAny. A number given another codomain byWithCodomaincan evaluate toNaN, so it keeps the cache.Equivalence
A verbatim copy of the 2.7.0 number-creation path is in the test project (
UnitTests/Core/NumberCreationAsOf270.cs); the number code is unchanged between v2.7.0 and master, and the copy was first run against the unchanged library and agreed on every case. Type,Equals, hash,ToStringand the decimal are compared through every entry point for:long.MinValue/MaxValue;All identical. A further test requires the new check to decide at least 99% of random doubles itself, so the comparison is not vacuous.
Before → after
net10.0 Release,
GC.GetAllocatedBytesForCurrentThread, warmed up, best of 5 × 200k:(Entity)double, ±0.5 to ±5e4(Entity)double, ±5e6(Entity)Complex(x, 0.5x)Real.Createin aDowncastingEnabled.Set(false)scope /CreateWithoutDowncastingEvaledon anInteger(Entity)doublethenEvaled(Entity)floatFloats are not helped: almost every float in ±5e4 is exactly a power-of-two ratio within the bound and becomes a
Rational, which is existing behaviour, and proving that cheaply would mean reproducing the old heuristic.The kernel performance gate passes on both master and the branch, every gated row within 3%.
Checks
Full check on the branch before the rebase onto 513304a (clean): UnitTests 19,962 → 19,980 (18 new), 0 failed; MCP 441, Terminal 69, F# 134, Interactive 19, all unchanged; AOT OK; BoundCheck 0 disagreements, RootCheck 596/596, CasBench 120/121 with 0 wrong, SimpSweep 10463/10463, RuleCheck clean, CanonCheck and Confluence at their baselines.
Not done
Why an
Integerfromlongcosts 432 B and aReal224 B: about 176 B of either is ten lazy caches onEntitythat a plain number never fills, and anIntegeralso stores anERationalbeside itsEInteger. The biggest saving is moving those caches into one object created on first use, but that is broad and moves allocation in both directions; the other options touch record equality or the public type hierarchy. None meets "no behaviour change, additive only" as it stands, so this is a proposal for a separate PR rather than code here.🤖 Generated with Claude Code