In continuation of the topic of computing mathematical functions explored in the lectures, we see another method to find square roots.
Suppose we wish to find the square root of some k > 0. Consider the sequence (a0, a1, a2...)
defined by
a0 = k
an+1 = (an + (k/an))/2 for n >= 0
It can be shown that as n increases, the an converges to the square root of k . Write a program that takes as input a double k, and computes its square root using this method. Compute the value of an till (an - an-1 < 1e-5) and then report an correct to 2 decimal places.
Note: Start writing the program directly from main_program. To print a double x correct to 2 decimal places, use
cout.precision(2);
cout << fixed << x << endl;
INPUT
k (2 <= k <= 100, of type double)
OUTPUT
The square root of k correct to two decimal places
SOLUTION:
int main()
{
double k, y, x;
cin >> k;
if (k < 2 || k > 100)
{
exit(0);
}
else
{
y = k;
x = (y + (k / y)) / 2;
while (y - x >= 0.00001)
{
y = x;
x = (y + (k / y)) / 2;
}
cout.precision(2);
cout << fixed << x << endl;
}
return 0;
}
Comments
Post a Comment