THINK FIRST·CODE LATER

← All labs

Your own square root: the Babylonian method

Problem

Long before computers, square roots were computed by repeating one formula: if guess is an approximation of √n, then

nextGuess = (guess + n / guess) / 2

is a better one. Start with 1 and stop when two guesses in a row differ by less than 0.00001.

Write MySqrt with the methods sqrt(double n), steps(double n) (how many times the guess was improved) and difference(a, b) (the distance between two numbers, written with an if). main reads numbers until the end of the input and compares your result with Math.sqrt. For the input

2 9 10 0.25 1000000 0

the program prints

sqrt(2.00): mine 1.41421 in 4 steps, Math.sqrt 1.41421
sqrt(9.00): mine 3.00000 in 6 steps, Math.sqrt 3.00000
sqrt(10.00): mine 3.16228 in 6 steps, Math.sqrt 3.16228
sqrt(0.25): mine 0.50000 in 5 steps, Math.sqrt 0.50000
sqrt(1000000.00): mine 1000.00000 in 15 steps, Math.sqrt 1000.00000
sqrt(0.00): mine 0.00000 in 0 steps, Math.sqrt 0.00000

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

l8-8-data-1.txt

2 9 10 0.25 1000000 0
What your program must print for l8-8-data-1.txt
sqrt(2.00): mine 1.41421 in 4 steps, Math.sqrt 1.41421
sqrt(9.00): mine 3.00000 in 6 steps, Math.sqrt 3.00000
sqrt(10.00): mine 3.16228 in 6 steps, Math.sqrt 3.16228
sqrt(0.25): mine 0.50000 in 5 steps, Math.sqrt 0.50000
sqrt(1000000.00): mine 1000.00000 in 15 steps, Math.sqrt 1000.00000
sqrt(0.00): mine 0.00000 in 0 steps, Math.sqrt 0.00000

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < l8-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content l8-8-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.