I'm trying to build a square root function to do square roots using the babylonian method, but getting the wrong result. I have the following code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
//base is the number being calculated, and is floating point.
calc=base/2;//first estimate way off.
last=0;
while(last!=calc && check!=base)
{
last=calc;
check=calc;
calc=base/calc;
calc=check+calc;
calc/=2;
check=calc*calc;
}
The Babalonian method of calculating the square root of 2 simply progressively averages the result from (x+2/x) where x is given some arbitrary value. The tolerance is applied to provide accuracy in this case to 7 decimal places
1 2 3 4 5 6 7 8
constdouble TOLERANCE = 5e-8;
double x=7;
while (fabs(x*x-2.0)>TOLERANCE)//absolute value function
{
cout<<x<<endl;
x=(x+2.0/x)/2;
}