何为"Newton's method"
牛顿法(英语:Newton's method)又称为牛顿-拉弗森方法(英语:Newton-Raphson method),它是一种在实数域和复数域上近似求解方程的方法。方法使用函数的泰勒级数 $fleft( x ight) $ 的前面几项来寻找方程 (fleft( x ight) =0) 的根。
方法说明
首先,选择一个接近函数(fleft(x ight)) 零点 [ 令(fleft(x ight)=0)) 的点] 的 (x_0),计算相应的 (fleft(x_0 ight)) 和该点的切线斜率,即对该点的函数求导得 (f'left( x_0 ight)) 。然后我们计算穿过点 ((x_0), (fleft(x_0 ight))) 并且斜率为 (f'left(x_0 ight)) 的直线和 (x) 轴的交点的横坐标,也就是求如下方程的解 [下面式子也恰好为 (fleft(x ight)=0) 的泰勒展开式的前两项 (fleft( x ight) =fleft( x_0 ight) +f'left( x_0 ight) left( x-x_0 ight) =0)]:
我们将新求得的点横坐标命名为 (x_1),通常 (x_1) 会比 (x_0) 更接近方程 (fleft(x ight)=0) 的解。因此 我们可以利用 (x_1) 进行下一轮的迭代。迭代公式可简化为:
图像示例:

示例
求方程 (cos left( x ight) -x^3=0) 的根。
由于 (-1le cos left( x ight) le 1) ,则 (-1le x^3le 1) , 即 (-1le xle 1) ,则 (0le cos left( x ight) le 1) ,因此 (0le x^3le 1) ,所以 (0le xle 1)。可知方程得根位于0和1之间。我们可以从 (x=0.5) 开始。
令 (fleft( x ight) =cos left( x ight) -x^3) ,两边求导,得 (f'left( x ight) =-sin left( x ight) -3x^2)。

牛顿法 VS 二分法
以求解立方根得问题为例:
解法一
求立方根的问题实际上就是在 1~给定数字 之间找到一个数,让这个数的立方近似等于给定数字,由此转化为了一个查找问题。
def binary_cubic_root(num):
low = 1
high = num / 2.0
mid = low
while high - low > 0.0001:
mid = (low + high) / 2.0
cubic = mid * mid * mid
if cubic < num:
low = mid
elif cubic > num:
high = mid
else:
break
return mid
解法二
求立方根得问题实际上就是解决 (x^3-k=0) 得解,其中 (k) 是给定已知得值,转化为牛顿迭代公式为:(x_{n+1}=x_n-frac{x_{n}^{3}-k}{3x_{n}^{2}}) 。
def newton_cubic_root(num):
# give an approximation of root
last = num
new = last - (last * last * last - num) / (3.0 * last * last)
while abs(new - last) > 0.0001:
last = new
new = last - (last * last * last - num) / (3.0 * last * last)
return new
为什么要用牛顿法?
牛顿迭代法的速度比二分法的速度要快。
time_1 = time.clock()
print("binary_search %.4f" % binary_cubic_root(12345678))
print(time.clock() - time_1)
time_2 = time.clock()
print("newton %.4f" % newton_cubic_root(12345678))
print(time.clock() - time_2)
binary_search 231.1204
3.419999999998424e-05
newton 231.1204
2.5200000000002998e-05