Skip to content

gh-162709: Signal Overflow for an out-of-range integer quotient in _pydecimal - #162720

Open
SudeepGowda55 wants to merge 2 commits into
python:mainfrom
SudeepGowda55:gh-162709-pydecimal-divint-overflow
Open

SudeepGowda55 wants to merge 2 commits into
python:mainfrom
SudeepGowda55:gh-162709-pydecimal-divint-overflow

Conversation

@SudeepGowda55

@SudeepGowda55 SudeepGowda55 commented Nov 27, 2026 •

Copy link
Copy Markdown

__floordiv__ returned the quotient from _divide() as is and __divmod__ only ran _fix() on the remainder, so a quotient that fits the precision but not Emax came back without Overflow. Both now run _fix() on the quotient too. remainder() still goes through _divide() directly and is unchanged.

The one exception is a finite number divided by an infinity: _decimal returns that 0 as is, without clamping it, so _fix() is skipped there.

To check this against _decimal, I ran divide_int, divmod and remainder over 120k random small contexts (all roundings, clamp 0/1, Emax 0-6) with _pydecimal on this branch and _decimal: results and flags match in every case, about 1,450 of them overflows. Before the change about 1 in 14 differed.

@python-cla-bot

This comment was marked as resolved.

Comment thread Lib/test/test_decimal.py Resolved
Comment thread Lib/_pydecimal.py
Comment on lines +1506 to +1508
if not other._isinfinity():
quotient = quotient._fix(context)
return quotient, remainder._fix(context)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if not other._isinfinity():
quotient = quotient._fix(context)
return quotient, remainder._fix(context)
return quotient._fix(context), remainder._fix(context)

The helper already has a special case for Infinity, right? It's not altered.

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_fix() special-cases an infinite self, but when the divisor is infinite the quotient is a finite zero, and _fix() would clamp it where _decimal does not:

c = Context(prec=4, Emax=2, Emin=-4, clamp=1, traps=[])
c.divide_int(Decimal("-8.91"), Decimal("Infinity"))
# _decimal: Decimal("-0"), no flags
# _fix() on the quotient: Decimal("-0.0"), Clamped

That case was most of the mismatches when I compared against _decimal with the unconditional _fix() (483 of 20k random contexts, all clamp=1 with an infinite divisor), so I kept the check.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I suggest you add test cases for this (and for __floordiv__).

Comment thread Lib/_pydecimal.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

2 participants