Javascript(55)
function f(n){for(i=x=99;i--;)x=(2*x+n/x/x)/3;return x}
奖金,所有根的通用配方
function f(n,p){for(i=x=99;i--;)x=x-(x-n/Math.pow(x,p-1))/p;return x}
对于立方根,只需使用f(n,3),平方根f(n,2)等等。示例:f(1024,10)return 2。
基于牛顿法的解释:
查找:f(x) = x^3 - n = 0,解决方案是n = x^3
推导:f'(x) = 3*x^2
重复:
x(i+1) = x(i) - f(x(i))/f'(x(i)) = x(i) + (2/3)*x + (1/3)*n/x^2
测验
[27,64,1,18.609625,3652264,0.001,7].forEach(function(n){console.log(n + ' (' + -n + ') => ' + f(n) + ' ('+ f(-n) +')')})
27 (-27) => 3 (-3)
64 (-64) => 4 (-4)
1 (-1) => 1 (-1)
18.609625 (-18.609625) => 2.65 (-2.65)
3652264 (-3652264) => 154 (-154)
0.001 (-0.001) => 0.09999999999999999 (-0.09999999999999999)
7 (-7) => 1.912931182772389 (-1.912931182772389)