You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
StorageMath.RootN returns one less than the exact root of a perfect power for short and int: RootN((short)15625, 6) is 4, RootN(1280000000, 7) is 19 #557
StorageMath.RootN gives a floor one too low for some exact powers in short and int. Each expected value below was checked against a BigInteger floor-root:
Call
Actual
Expected
StorageMath.RootN((short)15625, 6)
4
5 (5⁶ = 15625)
StorageMath.RootN((short)16384, 7)
3
4 (4⁷ = 16384)
StorageMath.RootN(893871739, 7)
18
19 (19⁷)
StorageMath.RootN(1280000000, 7)
19
20 (20⁷)
StorageMath.RootN(1801088541, 7)
20
21 (21⁷)
A 200k-sample fuzz over long, ulong, Int128, UInt128, byte and BigInteger found no other failures. Cbrt (degree 3) passed throughout.
CLAUDE.md says Cbrt and RootN "refine every integer type in integer arithmetic, so their floor is exact". So any quantity code that takes an integer root of a perfect power in short or int storage gets a result one unit too small.
Cause
RootByDescent (Semantics.Quantities/StorageMath.cs, ~L803-840) relies on the invariant that the estimate stays at or above the root. The overflow branch breaks it:
if(!TryPower(estimate,degree-1,outTpower)||T.IsZero(power)){// ... Halving reaches a range the type holds, and stays at or above the root.estimate=(estimate+T.One)/two;continue;}
Traced for (short)15625, degree 6:
The seed is 4, and 4⁶ = 4096 is below 15625, so the lift doubles it to 8. 8⁶ overflows short, so the lift stops.
8⁵ = 32768 overflows short, so the branch halves the estimate: (8+1)/2 = 4. That is below the root of 5.
The Newton step from 4 gives next = (5·4 + 15625/4⁵)/6 = (20 + 15)/6 = 5. Since next >= estimate, the loop returns the stale 4.
Halving is only safe while the halved value is still ≥ the root. Once the lift has doubled past the root, the value before doubling may have been the only thing known to be below it, and halving can drop back to that.
Suggested fix
Either of these:
In the overflow branch, bisect between the last estimate known to be below the root (the value before the lift's last doubling) and the current estimate, instead of halving blindly.
A test checks RootN for sbyte, short, int (and their unsigned counterparts) against a BigInteger floor-root at every exact power kᵈ the type holds, for degrees 4–10, and at kᵈ − 1.
Activity