Skip to content

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