Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I compute the square root of a number without using builtins? [duplicate]

how can I create a method that returns the sqrt of a given nunber?

For example: sqrt(16) returns 4 and sqrt(5) returns 2.3 ...
I am using Java and know the Math.sqrt() API function but I need the method itself.

like image 344
dato datuashvili Avatar asked Jun 16 '10 08:06

dato datuashvili


2 Answers

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");
    }

  }
}
like image 110
John Joshua Austero Lipio Avatar answered Oct 19 '22 09:10

John Joshua Austero Lipio


You will probably have to make use of some approximation method.

Have a look at

Methods of computing square roots

like image 32
Adriaan Stander Avatar answered Oct 19 '22 10:10

Adriaan Stander