Lab 5 — Floating Point sqrt

Lab Description:

This lab displays an algorithm called the Babylonian Algorithm which was originally created to solve the square root of numbers to a exact value. The square root function, and the Babylonian Algorithm are similar in values but the Babylonian Algorithm is limited to only tolerance in which you give it. You can not get a more precise accurate value unless changing the tolerance you work with. The way the program works is that you input a number, you want the square root of. Then the program will make an initial guess (using input/2). After, using the initial guess it will be used in this formula xn+1 = (xn + x/xn )/2 (Xn is initial guess) to obtain a closer value to the answer. The program will calculate Difference by then compare this new value with the initial guess( or any future guesses) Difference = xn+1xn. The program will repeat the equation xn+1 = (xn + x/xn )/2 using the latest guess, until the difference is less than the tolerance.

Code:

#include 
#include 
using namespace std;
int main()
{
    int i = 1;
    double t =.00001, x, sqrtDiff, difference, xo, xn; //tolerance xo intial guess and xn new guess
    
    cout<<"Enter in approximate to its square root"<>x;
    xo = x/2;
    xn = (xo + (x/xo))/2;
    difference = (abs(xn-xo));
    xo = xn;
    cout<<"Babylonian Square Root Approximate is "<< xn <<endl;
    cout<<"Difference between of x_n+1 - x_n: "<<difference<<endl;
    i++;
    cout<<"Iteration #"<<i< t)
    {
        xn = (xo + (x/xo))/2 ;
        difference = abs(xn-xo);
        xo = xn;
        cout<<"Babylonian Square Root Approxiamte is "<<xn<<endl;
        cout<<"Difference between of x_n+1 - x_n: "<<difference<<endl;
    i++;
        cout<<"Iteration #"<<i<<endl;
    }
    
    sqrtDiff = abs((sqrt(x)) - xn);
    cout<<"Using sqrt() the result is: "<<sqrt(x)<<endl;
    cout<<"Difference between sqrt() and babylonian is: "<<sqrtDiff<<endl;

return 0;
}

 

Screenshots:

Ubuntu

Leave a Reply

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