Skip to content

fix(stdlib): limit_denominator floors and breaks ties as CPython - #2781

Merged
antonsynd merged 2 commits into
devfrom
claude/fraction-limit-denominator
Nov 20, 2026
Merged

antonsynd merged 2 commits into
devfrom
claude/fraction-limit-denominator

Conversation

@antonsynd

@antonsynd antonsynd commented Nov 20, 2026 •

Copy link
Copy Markdown
Owner

Why

#2606 (lane:silent-wrong, reach:program): Fraction.limit_denominator disagreed with CPython in three ways:

  • Ties. On a tie it returned the other bound: Fraction(1, 2).limit_denominator(1) gave 1, where CPython gives 0.
  • Negative fractions. Every negative fraction that reached the continued-fraction loop threw an unhandled System.DivideByZeroException. BigInteger.DivRem truncates where Python's // floors. The lead posted these cells on Fraction.limit_denominator: wrong on ties, DivideByZeroException on a negative tie #2606 (comment 7050183488).
  • Silently wrong values. Some negative inputs did not crash but returned a wrong answer: 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).
  • Early return. It gave back the same object, where CPython's Fraction(self) makes a new one (g is f was True).

Change

Fraction.LimitDenominator now follows CPython 3.15's Fraction.limit_denominator line for line:

  • the max_denominator < 1 ValueError and its message;
  • the early return as a new, equal Fraction;
  • floored // for a and k, using the class's FloorDivRem;
  • CPython's single test 2*d*(q0+k*q1) <= denominator, which returns p1/q1 on a tie.

The PSF header's scope and Changes: lines and THIRD-PARTY-NOTICES entry 11 now describe a port of the whole method.

Expression CPython 3.15.2 dev head
Fraction(1, 2).limit_denominator(1) 0 1 0
Fraction(-1, 2).limit_denominator(1) -1 DivideByZeroException -1
Fraction(-1, 3).limit_denominator(2) -1/2 DivideByZeroException -1/2
Fraction(-7, 10).limit_denominator(3) -2/3 DivideByZeroException -2/3
Fraction(-22, 7).limit_denominator(5) -16/5 DivideByZeroException -16/5
Fraction(-0.1).limit_denominator(10) -1/10 -1801439850948198/18014398509481979 -1/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 set SHARPY_REQUIRE_PYTHON_ORACLE=1, so the test cannot skip there.

It covers 23,409 cells:

  • a grid of numerator −30..30 × denominator 1..30 × max_denominator 1..12 (21,960);
  • every exact tie: Farey F_m midpoints for m = 1..12, shifted by −3..2 (1,338);
  • 12 large values × 9 max_denominators up to 10**12 (108);
  • the refusal at 0 and −1;
  • the early-return identity.

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, and cmp showed the file identical.

Mutation Result
base (dev's method) red: 3,276 of 3,279 lines diverge; DivideByZeroException
truncating division (the loop's a; k cannot differ, since its dividend is never negative) red: 3,276 of 3,279 lines diverge
tie-break <= → < red: 1,711 of 3,279 lines diverge
early return this red: 1 line diverges
restored green

Gate

Local @ f59cd5990 (lane worker, measured, oracle CPython 3.15.2):

  • build: 0 warnings, 0 errors;
  • Stdlib Fraction|DoorCensus: 81/0/0;
  • the new differential test: 1/0/0;
  • Compiler Conformance|Infrastructure: 18,518/0/0;
  • format verify: clean;
  • notices/licences pytest: 62/0/0.

Fix round @ f901690e8 (comments and the regenerated docs/stdlib/fractions.md): Stdlib Fraction 73/0/0 (the differential test ran, oracle required), stdlib generate --check exit 0, format clean. CI at f59cd5990 was red only on stdlib 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

fractions is not on the Stdlib exception-escape sweep roster. Sharpy's except ZeroDivisionError does not catch an escaped System.DivideByZeroException; that belongs to the #2573 escape class.

Issues

sharpy-issues:
  closes: [2606]
  files: []

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 sharpyc against CPython 3.15.2: 24 expressions including floats, 50-digit and 36-digit values, 2**63-1 limits, refusals and the identity, all equal at the head. It checked that the divisor passed to FloorDivRem is always positive and that the tie comment holds (13,614 exhaustive ties), and confirmed the differential test cannot skip in CI's test-fast job.

Applied:

  1. The mutation row for truncating division names the loop's a: k's dividend is never negative, so its floor cannot be observed (comment reworded at k).
  2. "Why" names the silently wrong cell (Fraction(-0.1).limit_denominator(10)), not only crashes.
  3. CI's red stdlib generate --check (found by the lead from the job log): docs/stdlib/fractions.md regenerated.

Out of scope, reported to the owner, not filed here: to_double gives nan when both parts overflow a double (lead reproduced); floor_div/%/to_long throw OverflowException past int64; repr prints 1/2 (lead reproduced); hash varies per process, and Equals(double) disagrees with GetHashCode.

https://claude.ai/code/session_01LGMKZYKjCq2pTmNWtKf2hy


Generated by Claude Code

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants