Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Square_root_esimation The Babylonian algorithm to compute the square root of a n

ID: 3553463 • Letter: S

Question

Square_root_esimation

The Babylonian algorithm to compute the square root of a number "n" is as follows: Make a guess at the answer (you should use n/2 as your initial guess) Compute r = n / guess Set guess = (guess + r) / 2 Go back to step 2 for as many iterations as necessary. The more steps 2 and 3 are repeated, the closer "guess" will become to the square root of "n". Write a program that inputs an integer for "n", iterates through the algorithm until guess is within 1% of the previous guess and outputs the answer as a double. The user should be able to run as many numbers as they like. Negative numbers and 0's should be noted as errors and not computed.

Explanation / Answer

program
implicit none
interface
function mysqrt( v, x, e )
real :: mysqrt
real, intent( IN ) :: v, x, e
end function mysqrt
end interface
real :: x, a, e, xn
read (*, *) a
do
if ( a .LE. 0.0 ) exit
read (*, *) e
if ( e .LE. 0.0 ) exit
read (*, *) x
do
if ( x .LE. 0.0 ) exit
write (*,'(1X,"N=",F7.2," Start=",F7.2,
" Err=",F10.6," SQRT(N)=",
F10.6)') a, x, e, mysqrt( a, x, e )
read (*, *) x
enddo
read (*, *) a
enddo
print *, 'DONE'
stop
end program TEST
function mysqrt( v, x, e )
implicit none
real :: mysqrt
real, intent( IN ) :: v, x, e
real :: z, zn
z= x
do
zn = ( z + v / z ) / 2.0
if ( abs( zn - z ) .LE. e ) exit
z= zn
enddo
mysqrt = z
end function mysqrt

That is, if you supply the standard input source with:

3
.0001
1
3
0
4
.00001
1
2
4
0
0

The output should look like:

N= 3.00 Start= 1.00 Err= 0.000100 SQRT(N)= 1.732143
N= 3.00 Start= 3.00 Err= 0.000100 SQRT(N)= 1.732143
N= 4.00 Start= 1.00 Err= 0.000010 SQRT(N)= 2.000000
N= 4.00 Start= 2.00 Err= 0.000010 SQRT(N)= 2.000000
N= 4.00 Start= 4.00 Err= 0.000010 SQRT(N)= 2.000000

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote