Feb 16, 2012 at 7:22am UTC
Hi ,
The below program finds square root of a given number
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
double sqrroot(double val)
{
double i=0;
double temp1,temp2;
while (i*i<=val)
i=i+0.1;
temp1=i;
for (int j=0;j<15;j++)
{
temp2=val;
temp2=temp2/temp1;
temp2=temp2+temp1;
temp2=temp2/2;
temp1=temp2;
}
return temp2;
}
int main()
{
cout << sqrroot ( 2.0 ) << endl ;
cout << sqrroot ( 3.0 ) << endl ;
cout << sqrroot ( 5.0 ) << endl ;
cout << sqrroot ( 9.0 ) << endl ;
_getche();
return 0;
}
I am unable to understand this part of the code .
1 2 3 4 5 6 7 8
for (int j=0;j<15;j++)
{
temp2=val;
temp2=temp2/temp1;
temp2=temp2+temp1;
temp2=temp2/2;
temp1=temp2;
}
Can anyone give me a simple explanation .
Thankyou for your time .
Last edited on Feb 16, 2012 at 7:22am UTC
Feb 16, 2012 at 8:08am UTC
don't you understand what a for loop does? or do you want to know what happens inside the for loop?
Feb 16, 2012 at 8:40am UTC
I know looping constructs .
I want to know how the for loop get you the square root . The loop is made to
run predefined (15 ) no of times . Why is that ?
Feb 16, 2012 at 3:17pm UTC
thanks for the reply .
I think i was able to understand about the babylonian method .
But i dont understand why the loop runs 15 times .
Feb 16, 2012 at 3:33pm UTC
I'm guessing it's a precision issue. Taking the squareroot of a non-square usually results in an infinite amount of digits. Depending on the application, the required precision is just a few digits.
An iterated method will narrow down its precision at every iteration by fine-tuning based on the results of the previous step. Here they use 15, but you can probably pick any number depending on how precise you wish to be.
Feb 16, 2012 at 5:17pm UTC
Thanks , i feel now i have understood it after all the trouble with the help of
you all.