标签:http io ar os java sp on 代码 bs
Implement int sqrt(int x).
Compute and return the square root of x.
公式推导:
在x0处的值是f(x0),这个点的切线可以表示为
y = f`(x0)*(x - x0)+f(x0)
求得当y = 0的时候,x1 = x0 - f(x0)/f`(x0)
由此迭代下去可以收敛
public class Solution { public int sqrt(int x) { double t = x; double lamda = 1; double oldT = t; while (Math.abs(t * t - x) >= 0.000000000000001 && lamda > 0.00000000000000000000001) { t = (t + x / t) / 2; lamda /= 2; oldT = t; } return (int) (t); } }
标签:http io ar os java sp on 代码 bs
原文地址:http://my.oschina.net/zuoyc/blog/340286