Search code examples
pythonfloating-pointieee-754exponentmantissa

How do ldexp and frexp work in python?


The python frexp and ldexp functions splits floats into mantissa and exponent. Do anybody know if this process exposes the actual float structure, or if it requires python to do expensive logarithmic calls?


Solution

  • As for speed, here is a quick comparison

    $ python -m timeit -c 'from math import frexp' 'frexp(1.1)'
    100000 loops, best of 3: 3.7 usec per loop
    
    $ python -m timeit -c 'from math import log' 'log(1.1)'
    100000 loops, best of 3: 3.7 usec per loop
    
    $ python -m timeit -c 'from math import ldexp' 'ldexp(1.1,2)'
    100000 loops, best of 3: 3.5 usec per loop
    

    So there isn't a lot of difference detectable in python between frexp, log and ldexp in terms of speed. Not sure that tells you anything about the implementation though!