Posts Tagged ‘Approximation

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

19
Apr
09

[C++] Approximating Squares: Bakhshali Approximation

double BakhshaliApproximation(double value, int n)
{
	return (n+((value - n*n)/(2*n)))-(((value - n*n)/(2*n))*((value - n*n)/(2*n))/(2*(n+((value - n*n)/(2*n)))));
}

Usage:
Where Value = the square you wish to find and N = Closest perfect square to Value.

std::cout << BakhshaliApproximation(9.2345, 3) << "\n";

Would Output:
3.038832022859598

which is approx = Sqrt(9.2345)