Lab 5

Lab Descriptions:

This Lab consist of creating  a C++ program that will approximate the square root of a number using the Babylonian Algorithm.  We should compare the result between iterations and the exact value of square root provided by the function SQRT in the math.h library. We also should use a tolerance value at which when the difference is less than or equal to the tolerance the iterations stop. The program will display all the steps. 

Code:

#include
#include
using namespace std;

	
	long double Babylonian(long double n) {
	int count =0;
	long double x = n;
	long double y = 1;
	long double error = 0.000001;
	while(x - y > error)
	 {
		y = n/x;
		x = (x + y)/2;
		count++;
		cout<<"Iteration #:"<<count<<endl;
		cout<<"Babylonian approximation is: "<<x<<endl;
		cout<<"The difference is:"<<x-y<<endl;
		cout<<endl;
	}
	cout<<endl; cout<<"Babylonian Square root approximation of "<<n<<" is "<<x<<endl;
		return x;
						}
	int main() { long double n;
	cout<>n;
	Babylonian(n);
	cout<<"using the sqrt(n), the result is:"<<sqrt(n)<<endl;
	cout<<"The difference between sqrt(n) and the babylonian approximation is:"<<Babylonian(n)-sqrt(n)<<endl;
	return 0;
	}

Screen-shoots:

Screenshot from 2013-11-30 19:29:40

babylo

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *