Saturday 20 August 2016

Chapter 6 Exercise 22, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

**6.22 (Math: approximate the square root) There are several techniques for implementing the sqrt method in the Math class. One such technique is known as the Babylonian method. It approximates the square root of a number, n, by repeatedly performing a calculation using the following formula:

nextGuess = (lastGuess + n / lastGuess) / 2

When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root. The initial guess can be any positive value (e.g., 1). This value will be the starting value for lastGuess. If the difference between nextGuess and lastGuess is less than a very small number, such as 0.0001, you can claim that nextGuess is the approximated square root of n. If not, next- Guess becomes lastGuess and the approximation process continues. Implement the following method that returns the square root of n.

public static double sqrt(long n)

import java.util.Scanner;
 
 
public class ProgrammingExercise6_22 {
 
 public static void main(String[] args) {
  System.out.print("Enter a number:");
  Scanner input = new Scanner(System.in);
  long n = input.nextLong();
  System.out.println("\nThe square root of " + n + " is " + sqrt(n));
 
 }
 
 public static double sqrt(long n) {
  double lastGuess = 1, nextGuess = 1;
  int nOfG = 0;
 
  do {
   lastGuess = nextGuess;
   nextGuess = (lastGuess + (n / lastGuess)) / 2;
   nOfG++;
   System.out.println("Guess " + nOfG + " is " + nextGuess);
  } while (Math.abs(lastGuess - nextGuess) > 0.0001);
 
  return nextGuess;
 }
 
}

No comments :

Post a Comment