## Newton-Raphson Method估算函数的根

Newton-Raphson Method

f(x) = $x^2 - a$ 有根 $\sqrt{a}$ ,

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20  #include   int main(void){ int a,error; double x0,x1 = 1; do { printf("Input a positive integer: "); scanf("%d",&a); if (error = (a <=0)) printf("\nERROR: Do it again!\n\n"); } while (error);   while (x0 != x1) { x0 = x1; /* save the current value of x1 */ x1 = 0.5 * (x1 + a / x1); /* compute a new value of x1 */ } printf("%lf\n",x1); return 0; }

2010-01-11

?View Code RSPLUS
 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  newton <- function(fun, x0, tol=1e-7, niter=100) { fun.list = as.list(fun) var <- names(fun.list[1]) fun.exp = fun.list[[2]] diff.fun = D(fun.exp, var) df = list(x=0, diff.fun) df = as.function(df) for (i in 1:niter) { x = x0 - fun(x0)/df(x0) if (abs(fun(x)) < tol) return(x) x0 = x } stop("exceeded allowed number of iterations") }
> f = function(x) x^2 – 5
> newton(f, 4)
[1] 2.236068
> g = function(x) x^3 – 5
> newton(g, 4)
[1] 1.709976