Search code examples
pythonexponentiation

Using exponentiation **0.5 less efficient than math.sqrt?


A quote from "Python Programming: An Introduction to Computer Science"

We could have taken the square root using exponentiation **. Using math.sqrt is somewhat more efficient.

"Somewhat", but to what extent, and how?


Solution

  • Theoretically, hammar's answer and duffymo's answer are good guesses. But in practice, on my machine, it's not more efficient:

    >>> import timeit
    >>> timeit.timeit(stmt='[n ** 0.5 for n in range(100)]', setup='import math', number=10000)
    0.15518403053283691
    >>> timeit.timeit(stmt='[math.sqrt(n) for n in range(100)]', setup='import math', number=10000)
    0.17707490921020508
    

    Part of the problem is the . operation. If you import sqrt directly into the namespace, you get a slight improvement.

    >>> timeit.timeit(stmt='[sqrt(n) for n in range(100)]', setup='from math import sqrt', number=10000)
    0.15312695503234863
    

    Key word there: slight.

    Further testing indicates that as the number gets larger, the benefit you get from using sqrt increases. But still not by a lot!

    >>> timeit.timeit(stmt='[n ** 0.5 for n in range(1000000)]', setup='import math', number=1)
    0.18888211250305176
    >>> timeit.timeit(stmt='[math.sqrt(n) for n in range(1000000)]', setup='import math', number=1)
    0.18425297737121582
    >>> timeit.timeit(stmt='[sqrt(n) for n in range(1000000)]', setup='from math import sqrt', number=1)
    0.1571958065032959