Babylon challenge

Can you guys help me with this problem. I have no idea how to even start it.

The Babylonian method to calculate 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. Compute r = n / guess.
3. Set guess = (guess + r) / 2.
4. Go back to step 2.

For part 1, you just need to repeat 5 times and stop (you could do it without a loop, but use one anyway.) For part 2, repeat until the guess is within 1% of the previous guess. You may want to start with just 5 loops to test whether it is working properly, then change it to work until the error gets small.
I actually made a post of this the other day

http://www.cplusplus.com/forum/beginner/110866/#msg605356

I can modify the code slightly more though not sure what I was thinking

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>

double sqrt( const double S , const int PRECISION )
{
	double x = S; //starting value is x0 which I will make equal to the value will use for xn + 1
	
	for( int n = 1; n < PRECISION; ++n )
	{
		x = .5 * ( x + S / x );
	}
	
	return( x );
}

int main()
{
	std::cout << "Sqrt of 4 precision 10: " << sqrt( 4 , 10 ) << std::endl;
	std::cout << "Sqrt 224 precision 10: " << sqrt( 224 , 10 ) << std::endl;
	std::cout << "Sqrt 121 precision 10: " << sqrt( 121 , 10 ) << std::endl;
	std::cout << "Sqrt 12.34 precision 10: " << sqrt( 12.34 , 10 ) << std::endl;
	return( 0 );
}


MY formula is slightly different than yours though.

My formula is

x0 = S
xn+1 = 1/2( xn + s / xn )

Yours is

x0 = S
xn+1 = 1/2( xn + S )

Yours you have to find a new S each time I believe mine you can use the value that you are finding the sqrt of or a guess.

example sqrt of 24 for mine you can use 24 or anything you think is a good guess

Yours you have to change each time I believe

since you know
( 24 + 24 ) / 2 will always be 24
Topic archived. No new replies allowed.