Finding the square root of a number is a common operation in mathematics.
In Python, there are several ways to find the square root of a number. In this article, we will compare the performance of the math.sqrt()
function, and the **0.5
operation.
We will test the performance of these alternatives for 10,000,000 times, using process_time on the free Google Colab plan.
Square root with math.sqrt()
The math.sqrt()
function returns the square root of a number. It is defined in the math
module.
import time
import math
start = time.process_time()
for i in range(10_000_000):
math.sqrt(i / 100)
end = time.process_time()
print("math.sqrt() took", end - start, "seconds")
>>> math.sqrt() took 1.6173091829999997 seconds
Square root with **0.5
The **0.5
operation also returns the square root of a number. It uses the 0.5 exponent to calculate the square root, with a different implementation.
**0.5
is the operation you would use to find the square root of a number in Python without using the math
module. But how efficient is it?
import time
import math
start = time.process_time()
for i in range(10_000_000):
(i / 100) **0.5
end = time.process_time()
print("**0.5 took", end - start, "seconds")
>>> **0.5 took 1.8436232099999987 seconds
math.sqrt() vs **0.5: Verdict
On Google Colab and using floats, the math.sqrt()
function is 1.14x faster than the **0.5
operation. If you don’t need the math
module in your code, or don’t need to compute the square root of a number many times, you can safely use the **0.5
operator instead without much performance difference.