Monday, June 20, 2011

Square Root of Two

The Easy Way


double x=Math.pow(2,0.5);
System.out.println(x);


Newton's Method

class NewtonRootTwo
{
  public static void main(String[] args) throws Exception
  {
    double guess=1;

    for (int i=0;i<100;i++)  // maximum 100 passes, more than enough
    {
      System.out.println("guess["+i+"]="+guess);
      double nextGuess = (guess+2/guess)/2;
      if (nextGuess==guess) break;  // cannot improve precision further
      guess = nextGuess; 
    }
  }
}

Result

java NewtonRootTwo
guess[0]=1.0
guess[1]=1.5
guess[2]=1.4166666666666665
guess[3]=1.4142156862745097
guess[4]=1.4142135623746899
guess[5]=1.414213562373095



Higher Precision

Since the double data type provides very limited precision, we must use the BigDecimal class to get higher precision.
import java.math.BigDecimal;

class HighPrecisionRootTwo
{
  public static void main(String[] args) throws Exception
  {
    int precision=60;    // 60 decimal places

    BigDecimal guess=new BigDecimal("1.0");
    BigDecimal TWO = new BigDecimal("2.0");

    for (int i=0;i<100;i++)  // maximum 100 passes, adjust if necessary
    {
      System.out.println("guess["+i+"]="+guess);
      // nextGuess = ( guess + 2/guess ) / 2
      BigDecimal nextGuess = guess.add(
        TWO.divide(guess,precision,BigDecimal.ROUND_DOWN)).
        divide(TWO,precision,BigDecimal.ROUND_DOWN);

      if (nextGuess.compareTo(guess)==0) break;
      guess = nextGuess; 
    }
  }
}
java HighPrecisionRootTwo
guess[0]=1.0
guess[1]=1.500000000000000000000000000000000000000000000000000000000000
guess[2]=1.416666666666666666666666666666666666666666666666666666666666
guess[3]=1.414215686274509803921568627450980392156862745098039215686274
guess[4]=1.414213562374689910626295578890134910116559622115744044584905
guess[5]=1.414213562373095048801689623502530243614981925776197428498289
guess[6]=1.414213562373095048801688724209698078569671875377234001561013
guess[7]=1.414213562373095048801688724209698078569671875376948073176679



Computing Root Two to Million of Digits

The built in BigDecimal is just not fast enough. You will need to implement a faster BigDecimal class. "apfloat for java" may be a good choice.

No comments:

Post a Comment