Saturday, December 17, 2011

19-The Babylonian Method for Determining a Square Root of a Number

The Babylonian Method for Determining a Square Root of a Number
The following is a method which is used to calculate the square root of a postive number. To download click here: sqrt.java.
      import javax.swing.*;
      public class sqrt
      {
          public static void main(String args[])
          {
            String tempString=JOptionPane.showInputDialog("Enter a positive number");
            double number=Double.parseDouble(tempString);
            System.out.println("Square root of " + number+"="+sqrt(number));                     
          }
          public static double sqrt(double number)
          { //square root Babylonian method
                             
                    double estimate=number;
                    double divisor=2;
                //below 100 is arbitrary, for very small decimals  i values must be large
                    for(int i=0; i<100; i++)
                    {
                        estimate=number/divisor;      
                        estimate=(estimate+divisor)/2; //find average estimate & divisor
                        divisor=estimate;
                    }
                    return estimate;           
          }
      }

0 comments:

Post a Comment