Chapter 3 Exercise 1 Babylonian Algorithm. The Babylonian algorithm to compute t
ID: 3551062 • Letter: C
Question
Chapter 3 Exercise 1 Babylonian Algorithm. The Babylonian algorithm to compute the square root of a positive number n is as follows:
1. Make a guess at the answer (you can pick n/2 as your initial guess).
2. Computer = n / guess.
3. Set guess = (guess +r) / 2.
4. Go back to step 2 until the last two guess values are within 1% of each other. Write a program that inputs an integer for n, iterates through the Babylonian algorithm until the guess is within 1% of the previous guess, and outputs the answer as a double to two decimal places. Your answer should be accurate even for large values of n. INPUT and PROMPTS. The program prints "This program estimates square roots." and then prompts for a positive integer as follows: ("Enter an integer to estimate the square root of: " and then reads in the integer . OUTPUT . Each time a new guess is computed, the program prints ithe line "Current guess: g", where g is the current guess, printed out with no special formatting. The final output is "The estimated square root of x is y", where x is the integer that was read in and y is the value computed by the procedure described above, printed out to two decimal places and a toal of six characters . CLASS NAMES. Your program class should be called Babylonia
Explanation / Answer
/* Babylonia class */
import
java.util.Scanner;
public
class Babylonia
{
/* start main method */
public static void main(String[] args)
{
/* variables declaration */
int n;
double guess;
double r;
/* create an object for Scanner class */
Scanner input = new Scanner(System.in);
/* display a message to user */
System.out.println("This program estimates square roots.");
/* prompt the user for input */
System.out.print("Enter an integer to estimate the square root of: ");
n = input.nextInt();
System.out.println();
/* initial guess */
guess = n / 2.0;
r = 0;
do
{
/* Compute r = n / guess */
/* if statement */
if(guess != 0)
r = n / guess;
/* Set guess = (guess +r) / 2 */
guess = (guess + r) / 2;
/* display the current guess */
System.out.println("Current guess: " + guess);
/* repeat the loop until the last two guess values are within 1% of each other */
}while((r - guess > 0.01) || (guess - r > 0.01));
/* display the final result */
System.out.printf(" The estimated square root of %d is %4.2f", n, guess);
} /* end of main method */
} /* end of Babylonia class */
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.