牛顿法
y
−
f
(
x
0
)
=
f
′
(
x
)
(
x
1
−
x
0
)
y-f(x_0)=f^{'}(x)(x_1-x_0)
y−f(x0)=f′(x)(x1−x0)
令
y
=
0
y=0
y=0 ,
x
1
=
x
0
−
f
(
x
0
)
f
′
(
x
0
)
x_1 = x_0-\frac{f(x_0)}{f^{'}(x_0)}
x1=x0−f′(x0)f(x0)
迭代下来,
x
n
+
1
=
x
n
−
f
(
x
n
)
f
′
(
x
n
)
x_{n+1} = x_n-\frac{f(x_n)}{f^{'}(x_n)}
xn+1=xn−f′(xn)f(xn)
f
(
x
)
=
x
2
−
n
x
n
+
1
=
x
n
−
x
2
−
n
2
x
f(x)=x^2-n \\ x_{n+1} = x_n-\frac{x^2-n}{2x}
f(x)=x2−nxn+1=xn−2xx2−n
double sqrt(double n){
double epison = 0.00001;
double last = 0.0;
double res = 1.0;
while(abs(res-last)>ep){
last = res;
res = res - (res*res-n)/(2*res);
}
return res;
}
二分法
二分法就是取left和right的中间数 l e f t + r i g h t 2 \frac{left+right}{2} 2left+right,如果中间数的平方大于number,则在( l e f t left left, l e f t + r i g h t 2 \frac{left+right}{2} 2left+right)继续迭代二分法,如果中间数的平方小于number,则在( l e f t + r i g h t 2 \frac{left+right}{2} 2left+right, r i g h t right right)继续迭代二分法,知道满足求得满足精度的结果
double sqrt1(double x){
double EPSINON = 0.00001;
double low = 0.0;
double high = x;
double mid = (low+high)/2;
while((high-low)>EPSINON){
if((mid*mid)>x){
high = mid;
}
else if(mid*mid<x){
low = mid;
}
else{
return mid;
}
mid = (low+high)/2;
}
return mid;
}