Importing the math module only happens once, and you probably won't get much faster than the math module. There is also an older Stackoverflow question regarding Which is faster in Python: x**.5 or math.sqrt(x)?. It is not clear which method is faster.
Maybe take a look at NumPy and SciPy, not necessarily for the sqrt but if you're doing some heavy calculations they could be handy.
Answer from Mad Scientist on Stack OverflowImporting the math module only happens once, and you probably won't get much faster than the math module. There is also an older Stackoverflow question regarding Which is faster in Python: x**.5 or math.sqrt(x)?. It is not clear which method is faster.
Maybe take a look at NumPy and SciPy, not necessarily for the sqrt but if you're doing some heavy calculations they could be handy.
I'd think the math library would likely be as fast as anything you could write yourself. But if you want to write your own, here's one algorithm. I don't know Python, so I'll just write some pseudo-code.
function sqrt(x)
lastGuess=x/2
loop
guess=(lastGuess+x/lastGuess)/2
if abs(guess-lastGuess)<.000001 // or whatever threshold you want
exit loop
lastGuess=guess
return guess
and the pseudocode translated to Python:
def sqrt(x):
last_guess= x/2.0
while True:
guess= (last_guess + x/last_guess)/2
if abs(guess - last_guess) < .000001: # example threshold
return guess
last_guess= guess
sqrt without calculator
How to find square root accurately
Is there any down sides of using n**0.5 instead of math.squared(n) ? Besides readability?
What's the better way of taking the square root of a number?
Videos
In python, I am tasked with finding the floor square root of a number without using any built-in operators or functions. I have no idea how to start this, since using a for loop can only check the integer roots.
ex.
in : 8 out : 2 exp: sqrt(8) = 2.82842..., but floor(2.82842..) = 2