There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().
There is a better algorithm, which needs at most 6 iterations to converge to maximum precision for double numbers:
#include <math.h>
double sqrt(double x) {
if (x <= 0)
return 0; // if negative number throw an exception?
int exp = 0;
x = frexp(x, &exp); // extract binary exponent from x
if (exp & 1) { // we want exponent to be even
exp--;
x *= 2;
}
double y = (1+x)/2; // first approximation
double z = 0;
while (y != z) { // yes, we CAN compare doubles here!
z = y;
y = (y + x/y) / 2;
}
return ldexp(y, exp/2); // multiply answer by 2^(exp/2)
}
Algorithm starts with 1 as first approximation for square root value.
Then, on each step, it improves next approximation by taking average between current value y and x/y. If y = sqrt(x), it will be the same. If y > sqrt(x), then x/y < sqrt(x) by about the same amount. In other words, it will converge very fast.
UPDATE: To speed up convergence on very large or very small numbers, changed sqrt() function to extract binary exponent and compute square root from number in [1, 4) range. It now needs frexp() from <math.h> to get binary exponent, but it is possible to get this exponent by extracting bits from IEEE-754 number format without using frexp().
Why not try to use the Babylonian method for finding a square root.
Here is my code for it:
double sqrt(double number)
{
double error = 0.00001; //define the precision of your result
double s = number;
while ((s - number / s) > error) //loop until precision satisfied
{
s = (s + number / s) / 2;
}
return s;
}
Good luck!
Videos
Java program to find out square root of a given number without using any Built-In Functions
public class Sqrt
{
public static void main(String[] args)
{
//Number for which square root is to be found
double number = Double.parseDouble(args[0]);
//This method finds out the square root
findSquareRoot(number);
}
/*This method finds out the square root without using
any built-in functions and displays it */
public static void findSquareRoot(double number)
{
boolean isPositiveNumber = true;
double g1;
//if the number given is a 0
if(number==0)
{
System.out.println("Square root of "+number+" = "+0);
}
//If the number given is a -ve number
else if(number<0)
{
number=-number;
isPositiveNumber = false;
}
//Proceeding to find out square root of the number
double squareRoot = number/2;
do
{
g1=squareRoot;
squareRoot = (g1 + (number/g1))/2;
}
while((g1-squareRoot)!=0);
//Displays square root in the case of a positive number
if(isPositiveNumber)
{
System.out.println("Square roots of "+number+" are ");
System.out.println("+"+squareRoot);
System.out.println("-"+squareRoot);
}
//Displays square root in the case of a -ve number
else
{
System.out.println("Square roots of -"+number+" are ");
System.out.println("+"+squareRoot+" i");
System.out.println("-"+squareRoot+" i");
}
}
}
You will probably have to make use of some approximation method.
Have a look at
Methods of computing square roots
As far as I know of there are two methods to calculate the square root: newtons method and a modified binary search,. Which one would you say is better for a technical interview? I know that the binary search method is O(LogN) but what is the time complexity of newtons method? Is newtons method faster?
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
I need to write a function that returns the integer square root of a number but I keep getting an error with the following code:
func checkSquareRoot(_ number: Int) -> Int {
for i in 1...100 {
if number == i * i {
return i
}
}
}
print(checkSquareRoot(100))
Any advice would be greatly appreciated!
There is a famous mathematical method called Newton–Raphson method for finding successively better approximations to the roots.
Basically , this method takes initial value and then in successful iterations converges to the solution.You can read more about it here.
Sample code is attached here for your reference.
def squareRoot(n):
x=n
y=1.000000 #iteration initialisation.
e=0.000001 #accuracy after decimal place.
while x-y > e:
x=(x+y)/2
y=n/x
print x
n = input('enter the number : ')
squareRoot(n)
Here you can increase the accuracy of square root result by adding '0' digits in e and y after decimal place.
Also there are other methods like binary search for finding square roots like shown here.
here is the way you can get square root without using any inbuilt function of python.
def findSqrt(n):
sqrtNum = n / 2
temp = 0
while sqrtNum != temp:
temp = sqrtNum
sqrtNum = (n / temp + temp) / 2
return sqrtNum
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.
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