Topic
Idea
x^2 = acan change tox^2-a = 0question. The question to get the square root of the numberacan convert to the question that to find a numberxto makex^2-a=0(or very small number like 0.000001). Below method is to use Binary Search and keep narrowing the scope to find themid valueto fulfill equation. Themid valueis the square root of numbera.
C++ Solution
#include<iostream>
#include<math.h>
using namespace std;
double calculate_Square_Root(int n)
{
double mid =(double (n))/ 2;
double l = 0.0, r = 1.0;
while (fabs((mid*mid - (double)n)) > 0.000001)
{
if ((mid*mid - (double)n) > 0.000001)
{
r = mid;
mid = l + (r - l) /2;
}
else
{
l = mid;
mid = l + (r - l) / 2;
}
}
return mid;
}
int main(){
double res = calculate_Square_Root(7);
cout << "result: " << res << endl;
}