20
Apr
09

[C++] Approximating Squares: Babylonian Method

const double EPSILON = 1.0e-16;

double BabylonianMethod(double value, int& counter)
{
	counter = 1;
	double guess=value/2;
	double result = ((value/guess)+guess)/2;
	while(abs(result-guess)>EPSILON)
	{
		guess = result;
		result = ((value/guess)+guess)/2;
		counter++;
	}
	return result;
}

Usage:

	int counter;
	double value = 10;
	double res = BabylonianMethod(value, counter);
	std::cout << std::setprecision(16);
	std::cout << "Square root of " << value << " is " << res << "\n";
	std::cout << "Number of iterations is " << counter << "\n";

Would Output:
Square root of 10 is 3.16228
Number of iterations is 6

Advertisements

0 Responses to “[C++] Approximating Squares: Babylonian Method”



  1. Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: