Tried to code bisection method to compute square root of 2, till the difference between two consecutive steps is less than some specific value, say 10^{-11}, where tolerance variable is specified as 11.
But, inspite of choosing long double data type,am unable to get beyond 6 places after decimal.
The same result is obtained, if choose tolerance as 11, 30, 5.
Cannot understand the reason for that.
The reason for that is unclear, as know that can get infinite number of decimal digits in the decimal expansion of sqrt(2).
Am running on onlinegdb.com, using the C++ option.
Each of the three values of tolerance gave the result as: 1.41421.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int val, tolerance;
cout << "Input the values of the number whose square root need be found, and the tolerance limit in the number of digits, of integer variable: tolerance, giving tolerance limit as: 10^{-tolerance}" << endl;
cout<< "Enter the number, followed by the # tolerance digits."<< endl;
cin >>val>> tolerance;
if(val< 0)
exit(0);
else
{
long double low = 0, high = val;
long double mid = (low + high)/2;
int c = 0;
long double diff = 0;
while (!c)
{
if((mid*mid-val)<0)
diff = val - mid*mid;
if (diff <= pow(10, -1*tolerance))
{
c = 1;
cout << "Square root of 2= "<< mid<<endl;
}
else if(mid * mid > val)
{
high = mid;
mid = (low + high)/2;
}
else
{
low = mid;
mid = (low + high)/2;
}
}
}
return 0;
}