Sunday, January 18, 2009

Square Root without any built-in function (C++ Program)

Now, I am going to represent a program which requires no built-in function to find the square root of a given number.
But for it you should know a little bit about the mathematics (Calculus). I am implementing epsilon-delta theorem here to find the square root of user given number.
Using the same concept, you can make a program to find the cube root of any number without any built-in function.
So here it is...

#include "iostream.h"

float absolute(float a) {
return ( a < 0 ? -a : a );
}

int main()
{
float guess = 1.0;
float epsilon = 0.0001;
float x;

cin >> x;

while ( absolute ( guess * guess - x ) >= epsilon ) {
guess = (x / guess + guess) / 2.0;
}

cout << "Square Root = " << guess << endl;

return 0;
}

0 comments:

Post a Comment