-
Notifications
You must be signed in to change notification settings - Fork 205
Description
Our docs says:
More technically, mpmath represents a floating-point number as a 4-tuple (sign, man, exp, bc) where sign is 0 or 1 (indicating positive vs negative) and the mantissa is nonnegative; bc (bitcount) is the size of the absolute value of the mantissa as measured in bits. Though redundant, keeping a separate sign field and explicitly keeping track of the bitcount significantly speeds up arithmetic (the bitcount, especially, is frequently needed but slow to compute from scratch due to the lack of a Python built-in function for the purpose).
Since CPython 3.1 there is a such function. It's the int.bit_length() method.
Some timings:
$ python -m timeit -r11 -s 'from mpmath.libmp.libintmath import python_bitcount as bc' 'bc(1000)'
500000 loops, best of 11: 965 nsec per loop
$ python -m timeit -r11 -s 'from mpmath.libmp.libintmath import python_bitcount as bc' 'bc(10)'
500000 loops, best of 11: 930 nsec per loop
$ python -m timeit -r11 -s 'from mpmath.libmp.libintmath import python_bitcount as bc' \
-s 'from math import factorial;n=factorial(100)' 'bc(n)'
100000 loops, best of 11: 3.18 usec per loop
vs
$ python -m timeit -r11 '(1000).bit_length()'
5000000 loops, best of 11: 75.6 nsec per loop
$ python -m timeit -r11 '(10).bit_length()'
5000000 loops, best of 11: 74.9 nsec per loop
$ python -m timeit -r11 -s 'from math import factorial;n=factorial(100)' 'n.bit_length()'
5000000 loops, best of 11: 97.2 nsec per loop
So, using the bit_length() is clearly better and it's available for all backends. Does it make sense to keep now the bc field of the mpf tuple or it should be deprecated?