查找,如: a) high=>1.5 b) low=>1.4 c) mid => (high+low)/2=1.45 d) 1.45*1.45>2 ? high=>1.45 : low => 1.45 e) 循环到 c)
a) 前后两次的差值的绝对值<=0.0000000001, 则可退出
const double EPSILON = 0.0000000001; double sqrt2() { double low = 1.4, high = 1.5; double mid = (low + high) / 2; while (high - low > EPSILON) { if (mid * mid > 2) { high = mid; } else { low = mid; } mid = (high + low) / 2; } return mid; }
xn+1 = xn-f(xn)/f'(xn)
对于本题,需要求解的问题为:f(x)=x2-2 的零点
EPSILON = 0.1 ** 10 def newton(x): if abs(x ** 2 - 2) > EPSILON: return newton(x - (x ** 2 - 2) / (2 * x)) else: return x
原文链接:http://codingdict.com/blog/228