Topic
Idea
x^2 = a
can change tox^2-a = 0
question. The question to get the square root of the numbera
can convert to the question that to find a numberx
to 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 value
to fulfill equation. Themid value
is 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;
}