kaki
kaki

Reputation: 1053

How to perform square root without using math module?

I want to find the square root of a number without using the math module,as i need to call the function some 20k times and dont want to slow down the execution by linking to the math module each time the function is called

Is there any faster and easier way for finding square root?

Upvotes: 17

Views: 82839

Answers (11)

cabavyras
cabavyras

Reputation: 59

bit too late to the party, but anyways I would like to mention these simple arithmetics:

25**(1/2)

or

pow(25, 0.5)

This will return as 5.0 Enjoy.

Upvotes: 2

Mad Scientist
Mad Scientist

Reputation: 18553

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.

Upvotes: 33

srikanth Gattu
srikanth Gattu

Reputation: 23

the below code is to find the square root of a number without using built in methods using python.the code is very simple to understand because i wrote the code using mathematics simple solution.

 x=float(input())
 min1=0 
 max1=x
 for i in range(10):
     mid=(min1+max1)/2  #middle value
     res=mid**2       #finding the square of middle value
     if res==x:       #if the middle value is square root program break here
        break        
     elif res>x:      #if the square value of the middle value is more than x then we need to take max value as middle 
        max1=mid
     else:                  #if the square value of the middle value is less than x then we need to take min  value as middle 
        min1=mid

 print(mid)
  

Upvotes: 0

Davis Tanugraha
Davis Tanugraha

Reputation: 21

Square Root Function

 def sqrt(number):
    if number ** 0.5 == int(number ** 0.5):
      return True
    else:
      return False

Upvotes: 2

user4169673
user4169673

Reputation:

You should type this line inside Jupyter Notebook:

25**(1/2)

Upvotes: 7

Sarvesh Jayaraman
Sarvesh Jayaraman

Reputation: 53

Python code snippet for computing square. It first makes an initial guess, and if the guess is not good enough it iterates until we have a good guess

def gen_square_root_v1(number, epsilon):

   #boundary condition check

   if number == '1':
      return 1

   elif number <= 0:
      print('this computes square root for positive numbers only' )

   else:
      pass


   prev_estimate = number/2

   while True: 

       #each itearation, calculate a new estimate
       new_estimate = (prev_estimate + number/prev_estimate)/2

       #Alternatively can use if abs(new_estimate - prev_estimate) < epsilon:

       #check the difference between  square of new_estimate and number
       if abs(new_estimate * new_estimate - number) < epsilon:
         return prev_estimate

     #if guess is not good enough, use it to make the next guess           
     prev_estimate = new_estimate


#call the function    
print(gen_square_root_v1(16,1e-5))

Upvotes: 0

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94475

As Fabian said, it's hard to be faster than math.sqrt. The reason is that it calls the correspond function from the C library, with CPython.

However, you can speed things up by removing the overhead of attribute lookup:

from math import sqrt

Each subsequent call to sqrt will not have to look it up in the math module, which saves execution time:

print sqrt(2)

Here are timing numbers, from the fastest to the slowest (Python 2.6.5, Mac OS X 10.6.3): sqrt is faster than **0.5:

lebigot@weinberg ~ % python -m timeit -s 'from math import sqrt; x = 2' 'sqrt(x)'
1000000 loops, best of 3: 0.207 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'x = 2' 'x**0.5'
1000000 loops, best of 3: 0.226 usec per loop
lebigot@weinberg ~ % python -m timeit -s 'import math; x = 2' 'math.sqrt(x)'
1000000 loops, best of 3: 0.268 usec per loop

Note that the timing tests calculate the square root of a variable. They do not calculate a constant like 2**0.5, because 2**0.5 is pre-calculated, in CPython:

import dis

def f():
    return 2**0.5

print dis.dis(f)

prints

2           0 LOAD_CONST               3 (1.4142135623730951)
            3 RETURN_VALUE        

where you see the constant float sqrt(2) = 1.414…

If you manipulate arrays of numbers, NumPy's sqrt is the way to go, as mentioned in another answer.

Upvotes: 12

Jay
Jay

Reputation: 27464

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

Upvotes: 12

Seth
Seth

Reputation: 46423

Use the power operator, and raise your numbers to the 1/2 power:

>>> 2**0.5
1.4142135623730951

As to whether it's faster:

>>> timeit.timeit(stmt='sqrt(x)', setup='from math import sqrt; x = 2')
0.7182440785071833
>>> timeit.timeit(stmt='x**0.5', setup='from math import sqrt; x = 2')
0.87514279049432275

Upvotes: 4

Jay
Jay

Reputation: 14461

In some special cases you can trade program size for blistering speed. Create a large array and store the pre-calculated result for every square root operation (using the input value as the index). It's pretty limited but you won't get anything faster.

(That's how quake did it)

Upvotes: 5

lhf
lhf

Reputation: 72312

You could implement Newton's method but, though it's really fast, it's unlikely to be faster than the C version which I assume is implemented in the math module. See http://en.wikipedia.org/wiki/Methods_of_computing_square_roots .

Upvotes: 3

Related Questions