Fix Python – Which is faster in Python: x**.5 or math.sqrt(x)?


Asked By – Nope

I’ve been wondering this for some time. As the title say, which is faster, the actual function or simply raising to the half power?


This is not a matter of premature optimization. This is simply a question of how the underlying code actually works. What is the theory of how Python code works?

I sent Guido van Rossum an email cause I really wanted to know the differences in these methods.

My email:

There are at least 3 ways to do a square root in Python: math.sqrt, the
‘**’ operator and pow(x,.5). I’m just curious as to the differences in
the implementation of each of these. When it comes to efficiency which
is better?

His response:

pow and ** are equivalent; math.sqrt doesn’t work for complex numbers,
and links to the C sqrt() function. As to which one is
faster, I have no idea…

Now we will see solution for issue: Which is faster in Python: x**.5 or math.sqrt(x)?


math.sqrt(x) is significantly faster than x**0.5.

import math
N = 1000000
for i in range(N):

10 loops, best of 3: 156 ms per loop

for i in range(N):

10 loops, best of 3: 91.1 ms per loop

Using Python 3.6.9 (notebook).

This question is answered By – Claudiu

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0