Skip to content

fix(maths): avoid intermediate overflow in geometric sums - #15806

Open
lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/geometric-sum-intermediate-overflow
Open

lanqing431 wants to merge 1 commit into
TheAlgorithms:masterfrom
lanqing431:fix/geometric-sum-intermediate-overflow

Conversation

@lanqing431

Copy link
Copy Markdown

Describe your change

  • Add an algorithm?
  • Fix a bug or typo in an existing algorithm?
  • Add or change doctests? -- Note: Please avoid changing both code and tests in a single pull request.
  • Documentation change?

Dividing first creates a float. Multiplying that float by a very large integer power subsequently raises OverflowError, even when the final quotient is representable as a float.

Evaluate the integer numerator before the division, avoiding premature float conversion. Preserve the existing zero-first-term result and all original doctest outputs.

Reproduction / verification

import math
from maths.sum_of_geometric_progression import sum_of_geometric_progression

assert math.isclose(sum_of_geometric_progression(1, 10**200, 2), 1e200)
assert math.isclose(sum_of_geometric_progression(1, -10**200, 2), -1e200)
assert sum_of_geometric_progression(0, 10**200, 3) == 0.0

Validated on Windows with CPython 3.15.2:

  • python -m doctest -v maths/sum_of_geometric_progression.py
  • python -m pytest maths/sum_of_geometric_progression.py --doctest-modules -q
  • python -m ruff check maths/sum_of_geometric_progression.py (Ruff 0.17.3)
  • python -m ruff format --check maths/sum_of_geometric_progression.py
  • Independent local regression checks: 185 checks: finite large-power results, zero first terms, small integer progressions compared with direct summation, and the documented negative-exponent example.

The regression harness found 3 failing cases on the unchanged upstream file and none after the fix (185 checks). It is kept outside this source-only diff to follow the repository's instruction not to change implementation and doctests together. The original doctests remain unchanged. The complete repository suite and free-threaded CI were not run locally.

Checklist

  • I have read CONTRIBUTING.md and AGENTS.md.
  • This PR only changes one algorithm file.
  • Existing doctests pass and are unchanged.
  • The modified file passes Ruff lint and formatting checks.
  • CI checks have completed. (Not run until this PR is opened.)

AI assistance: OpenAI Codex assisted with source analysis, implementation, reproductions, local verification, and drafting this description.

This branch has not been deployed

No deployments
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.

1 participant