Repository navigation
fix(stdlib): limit_denominator floors and breaks ties as CPython - #2781
Merged
Merged
Conversation
Fraction.LimitDenominator now follows CPython 3.15's fractions.Fraction.limit_denominator line for line: the max_denominator < 1 ValueError and its message, the early return as a new equal Fraction (Fraction(self)), floored // in the continued-fraction loop and for k (the class's FloorDivRem, Python's divmod for a positive divisor), and the single 2*d*(q0+k*q1) <= denominator test, which returns p1/q1 on a tie. BigInteger.DivRem truncated, so every negative input that reached the loop threw System.DivideByZeroException, and the cross-multiplied comparison returned the other bound on a tie. The PSF header's scope and Changes lines and the THIRD-PARTY-NOTICES entry now describe the whole-method port. Test: FractionLimitDenominatorDifferentialTests (Sharpy.Stdlib.Tests) generates one program, runs it under CPython 3.15 and under Sharpy, and compares every line: numerator -30..30 x denominator 1..30 x max_denominator 1..12 (21960 cells), every exact tie as the midpoint of consecutive Farey F_m terms for m 1..12 shifted by -3..2 (1338 cells), 12 large values x 9 max_denominators up to 10**12 (108 cells), the refusal at 0 and -1 (2), and the early-return identity (1): 23409 cells. Mutation record (each restored with cp from a saved copy, then cmp): - base (dev's LimitDenominator) -> red: 3276 of 3279 lines diverge, DivideByZeroException at the first negative row; restored, cmp equal. - revert floor division (BigInteger.DivRem in the loop, truncating BigInteger.Divide for k) -> red: 3276 of 3279 lines, the same DivideByZeroException; restored, cmp equal -> green. - flip the tie-break (<= to <) -> red: 1711 of 3279 lines diverge (e.g. grid -30 4 at m=1: -7 for CPython's -8); restored, cmp equal. - early return as `return this` -> red: 1 line, `early True True` for CPython's `early True False`; restored, cmp equal -> green. Refs #2606 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
CI's Python build-tools gate was red at f59cd59: `stdlib generate --check` found docs/stdlib/fractions.md out of date, because the new LimitDenominator doc comment feeds that generated page. The page is regenerated with `python -m build_tools stdlib generate --force`, and the doc comment is reworded for Sharpy readers: max_denominator, not the C# parameter name, plus the ValueError refusal. Review nit: k = (max_denominator - q0) // q1 has a non-negative dividend and q1 >= 1 (the loop always runs once), so floored and truncating division agree there, and reverting k's floor can never be detected. The comments now say only the loop's `a` floor is load-bearing; k keeps FloorDivRem as the port's spelling of //. This corrects f59cd59's mutation record: its "revert floor division" red came from `a` alone. Refs #2606 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
This was referenced Nov 20, 2026
This was referenced Nov 20, 2026
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.
Why
#2606 (lane:silent-wrong, reach:program):
Fraction.limit_denominatordisagreed with CPython in three ways:Fraction(1, 2).limit_denominator(1)gave1, where CPython gives0.System.DivideByZeroException.BigInteger.DivRemtruncates where Python's//floors. The lead posted these cells on Fraction.limit_denominator: wrong on ties, DivideByZeroException on a negative tie #2606 (comment 7050183488).Fraction(-0.1).limit_denominator(10)gave-1801439850948198/18014398509481979, whose denominator is far above the limit. CPython gives-1/10(found by the independent review, measured on both builds).Fraction(self)makes a new one (g is fwasTrue).Change
Fraction.LimitDenominatornow follows CPython 3.15'sFraction.limit_denominatorline for line:max_denominator < 1ValueError and its message;//foraandk, using the class'sFloorDivRem;2*d*(q0+k*q1) <= denominator, which returnsp1/q1on a tie.The PSF header's scope and
Changes:lines and THIRD-PARTY-NOTICES entry 11 now describe a port of the whole method.Fraction(1, 2).limit_denominator(1)Fraction(-1, 2).limit_denominator(1)Fraction(-1, 3).limit_denominator(2)Fraction(-7, 10).limit_denominator(3)Fraction(-22, 7).limit_denominator(5)Fraction(-0.1).limit_denominator(10)The CPython column was measured by the lane worker and re-run by the lead. The dev and head columns were measured by the lane worker with a built
sharpyc run.Test
FractionLimitDenominatorDifferentialTests(Sharpy.Stdlib.Tests) generates one program, runs it under CPython 3.15 and under Sharpy, and compares every line. CI's .NET jobs setSHARPY_REQUIRE_PYTHON_ORACLE=1, so the test cannot skip there.It covers 23,409 cells:
Positive controls cover the refusal, a positive and a negative tie, and the identity. The test also checks CPython's line count against the Farey formula.
Mutation record
Each mutation was restored with
cp, andcmpshowed the file identical.a;kcannot differ, since its dividend is never negative)<=→<return thisGate
Local @
f59cd5990(lane worker, measured, oracle CPython 3.15.2):Fraction|DoorCensus: 81/0/0;Conformance|Infrastructure: 18,518/0/0;Fix round @
f901690e8(comments and the regenerateddocs/stdlib/fractions.md): StdlibFraction73/0/0 (the differential test ran, oracle required),stdlib generate --checkexit 0, format clean. CI atf59cd5990was red only onstdlib generate --check(fractions.md out of date after the doc-comment change).CI gate: 85,542 passed / 0 failed / 10 skipped @
f901690e8(run 44823510669, measured); Gate (Python build tools) green.Not changed here
fractionsis not on the Stdlib exception-escape sweep roster. Sharpy'sexcept ZeroDivisionErrordoes not catch an escapedSystem.DivideByZeroException; that belongs to the #2573 escape class.Issues
Independent review
Independent review @ f59cd59: merge; 3 applied, 0 declined (reasons below); fixes f59cd59..f901690 read by the lead
A fresh reviewer ran the head and base
sharpycagainst CPython 3.15.2: 24 expressions including floats, 50-digit and 36-digit values,2**63-1limits, refusals and the identity, all equal at the head. It checked that the divisor passed toFloorDivRemis always positive and that the tie comment holds (13,614 exhaustive ties), and confirmed the differential test cannot skip in CI'stest-fastjob.Applied:
a:k's dividend is never negative, so its floor cannot be observed (comment reworded atk).Fraction(-0.1).limit_denominator(10)), not only crashes.stdlib generate --check(found by the lead from the job log):docs/stdlib/fractions.mdregenerated.Out of scope, reported to the owner, not filed here:
to_doublegivesnanwhen both parts overflow a double (lead reproduced);floor_div/%/to_longthrow OverflowException past int64;reprprints1/2(lead reproduced);hashvaries per process, andEquals(double)disagrees withGetHashCode.https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy
Generated by Claude Code