CET 3510 Lab 5

Objective: The objective of this experiment was to further observe and analyze c language by using C++ to create a square root calculator. The calculator used both the math library provided in C++ and a Babylonian algorithm in order to compare the accuracy between the two.

Code: The source code below is what was used to create the program.

//Lab 5
//Shinquella Glasgow
//This proram finds the square root of a number using Babylonian math
#include <iostream>
#include <math.h>
using namespace std;
int main ()
{
	double diff=1;
	double x=0;
	double g1=0;
	double g2=0;
	double t=0.00001;

	cout<<"Enter a value to find the square root"<<x;
     cin>>x;

		g1=x/2;
//A while loop is used to repeaedly perform the math until the answer satisfies the tolerance
		while (t<=diff)
		{
			g2=(g1 + (x/g1))/2; //formula for Babylonian math
				diff=(g2-g1);
					g1=g2;

				cout<<"Babylonian square root is"<<g1<<endl;
				cout<<"Actual value is"<<sqrt(x)<<endl;
		}
	}

Screenshot: The image below is what the program looks like once it is executed in the terminal.

shot-2013-12-10_22-42-59

Leave a Reply

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