+ 2
Do we have any Algorithm to implement the code in C for Square Root Calculation of Numbergiven by user? Without Using An Inbuilt
Square root 25=5 2=1.414213562 9=3 And 3=1.732050808 ...etc.
2 Antworten
+ 1
I have tried an approximation using to variables y and y2 moving around the square root of x. :
#include <iostream>
using namespace std;
double abs(double x){
return x>0.0 ? x : -x;
}
double my_sqrt(double x){
double y,ay,d,ad,e,p;
if (x<0.0){
return 0.0;
}
y=x/4.0;
ay=x/2.0;
p=x/1e20;
e=ay-y;
while(e*e>p)
{
d=y*y-x;
ad=ay*ay-x;
if ((d>0.0) && (ad>0.0)) {
e=ay-y;
y-=e;
ay-=e;
}
else if ((d<0.0) && (ad<0.0)){
e=ay-y;
y+=e;
ay+=e;
}
else if (d<=0 && ad>=0){
y=(2.0*y+ay)/3.0;
ay=(2.0*ay+y)/3.0;
e=(ay-y);
}
else {
return -1;
}
if (y<0) y=0;
if (ay<0) return -1;
cout<<y<<";"<<ay<<";"<<e<<endl;
}
return y;
}
int main() {
cout<<my_sqrt(10)<<endl;
return 0;
}
0
I would look at either the cmath or math.h libraries, for c++ or c respectively. They have built in functions that allow you to find the square root of a double.
For example sqrt (25.0) = 5.
If you are looking for an actual algorithm to compute a square root without these libraries I would go to Google as it can be complex depending on the algorithm you look at.