Skip to content

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
Rafael-SOWNet merged 3 commits into
masterfrom
perf/cheaper-number-creation
Nov 15, 2026
Merged

Rafael-SOWNet merged 3 commits into
masterfrom
perf/cheaper-number-creation

Conversation

@Rafael-SOWNet

Copy link
Copy Markdown
Member

Three commits, one per change, meant to be merged as they are (rebase, not squash). No answer changes, so there is no BREAKING-CHANGES.md entry.

  1. A double that is provably no small rational is a Real without the search. A double is m/2^k, so its continued fraction runs exactly on two machine integers. Real.IsProvablyNoSmallRational (in MachineNumbers.cs) answers "Real" only where it proves the old code would return that same Real: 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.
  2. Real.CreateWithoutDowncasting(EDecimal), a public, additive way to make a Real without a DowncastingEnabled scope. Named this way rather than Create(value, bool downcast), since downcast: true would read as forcing downcasting while the setting is off, which Create does not do.
  3. A number's Evaled is the number, without caching it, for a number with its own default codomain or Any. A number given another codomain by WithCodomain can evaluate to NaN, 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, ToString and the decimal are compared through every entry point for:

  • 1M random bit patterns, and 1M values (r − ½)·10^k for k in −30..30;
  • every p/q with |p| ≤ q < 1000, and 200k doubles near ratios with denominators up to 2e8;
  • 1–8 ulps around short decimals, and 16 ulps around 2^53, 2^62, 2^63 and long.MinValue/MaxValue;
  • values near 1e-16 and 1e-50, subnormals, ±0, NaN, ±∞;
  • 600k floats and 300k complex numbers;
  • those edge sets plus 60k random values under each of 20 settings, including precision 30 and 300.

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:

before after
(Entity)double, ±0.5 to ±5e4 1096–1117 B, 0.45–0.58 µs 616 B, 0.15–0.19 µs
(Entity)double, ±5e6 2254 B, 1.11 µs 615 B, 0.13 µs
(Entity)Complex(x, 0.5x) 3217 B, 1.38 µs 2227 B, 0.51 µs
Real.Create in a DowncastingEnabled.Set(false) scope / CreateWithoutDowncasting 336 B (+112 B scope), 0.078 µs 224 B, 0.015 µs
first Evaled on an Integer +40 B, 0.130 µs +0 B, 0.049 µs
(Entity)double then Evaled 1157 B, 0.60 µs 616 B, 0.155 µs
(Entity)float 39,895 B, 18.2 µs unchanged

Floats 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 Integer from long costs 432 B and a Real 224 B: about 176 B of either is ten lazy caches on Entity that a plain number never fills, and an Integer also stores an ERational beside its EInteger. 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

Rafael-SOWNet and others added 3 commits November 15, 2026 20:02
(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

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 92.24806% with 10 lines in your changes missing coverage. Please review.
✅ Project coverage is 86.98%. Comparing base (513304a) to head (fa90da0).

Files with missing lines Patch % Lines
...th/Core/Entity/Continuous/Number/MachineNumbers.cs 92.45% 4 Missing and 4 partials ⚠️
Sources/AngouriMath/Convenience/MathS.cs 50.00% 1 Missing ⚠️
.../Continuous/Entity.Continuous.Number.Definition.cs 66.66% 1 Missing ⚠️
Additional details and impacted files

Impacted file tree graph

@@            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     
Flag Coverage Δ
cpp 37.77% <ø> (ø)
csharp 87.51% <92.24%> (+<0.01%) ⬆️
fsharp 32.97% <ø> (ø)
interactive 39.81% <ø> (ø)

Flags with carried forward coverage won't be shown. Click here to find out more.

Files with missing lines Coverage Δ
...Continuous/Entity.Continuous.Complex.Definition.cs 83.49% <100.00%> (+1.31%) ⬆️
...ty/Continuous/Entity.Continuous.Real.Definition.cs 89.33% <100.00%> (+0.14%) ⬆️
...ngouriMath/Core/Entity/Entity.ImplicitOperators.cs 100.00% <100.00%> (ø)
...Math/Functions/Evaluation/Evaluation.Definition.cs 90.98% <100.00%> (+0.07%) ⬆️
Sources/AngouriMath/Convenience/MathS.cs 90.69% <50.00%> (ø)
.../Continuous/Entity.Continuous.Number.Definition.cs 33.33% <66.66%> (+11.11%) ⬆️
...th/Core/Entity/Continuous/Number/MachineNumbers.cs 92.45% <92.45%> (ø)

... and 4 files with indirect coverage changes

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Rafael-SOWNet
Rafael-SOWNet merged commit e5f544f into master Nov 15, 2026
35 checks passed
@github-project-automation github-project-automation Bot moved this from Todo to Done in AngouriMath Nov 15, 2026
@Rafael-SOWNet
Rafael-SOWNet deleted the perf/cheaper-number-creation branch November 15, 2026 20:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

1 participant