Sqrt(x) Float
Description:
Example:
Note
Idea:
牛顿法。start的数是x/2。
x(n+1) = xn - f(xn)/f'(xn)
x=sqrt(a), f(x) = x*x - a
, find root
x=1/2( xn + a/xn )
Code:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
double findRoot(double num){
if(num<0){
return 0;
}
double xn=num/2.0;
double xn2=1/2.0*(xn+num/xn);
while(abs(xn2-xn)>10e-10){
xn=xn2;
xn2=1/2.0*(xn+num/xn);
}
return xn2;
}
int main(){
cout<<findRoot(5);
}