Skip to content

bpo-37295: Speed up math.comb(n, k) for 0 <= k <= n <= 67 #30275

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 28, 2021

Conversation

mdickinson
Copy link
Member

@mdickinson mdickinson commented Dec 27, 2021

This PR speeds up math.comb(n, k) for very small k and n.

The existing tests already include exhaustive testing of correctness of math.comb(n, k) for 0 <= k <= n <= 100, so I didn't add any more unit tests.

Some sample timings on my machine (comparing commit fd3a4bb on this branch with commit 2e3e0d2 on the main branch):

./python.exe -m timeit -s "from math import comb;n, k = 1, 1" "comb(n, k)": difference not significant

  • main: 5000000 loops, best of 5: 35.5 nsec per loop
  • here: 10000000 loops, best of 5: 34.2 nsec per loop

./python.exe -m timeit -s "from math import comb;n, k = 5, 3" "comb(n, k)": ~23% faster (but may not be significant)

  • main: 5000000 loops, best of 5: 38.6 nsec per loop
  • here: 10000000 loops, best of 5: 31.5 nsec per loop

./python.exe -m timeit -s "from math import comb;n, k = 67, 25" "comb(n, k)": ~9.7x faster

  • main: 500000 loops, best of 5: 447 nsec per loop
  • here: 5000000 loops, best of 5: 46.1 nsec per loop

https://bugs.python.org/issue37295

Fix array name in a comment; be consistent about operator spacing.
Copy link
Member

@tim-one tim-one left a comment

Choose a reason for hiding this comment

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

Very nice and very clear. Ship it 😃

@mdickinson mdickinson merged commit 02b5417 into python:main Dec 28, 2021
@mdickinson mdickinson deleted the faster-math-comb-for-tiny-inputs branch December 28, 2021 12:26
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.

5 participants