fun <- function(x) { sin(x)/(x) } curve(fun,-10,10) fun <- function(x) { log(x+1)/(x+1) } curve(fun,0,3) der <- function(x) { (fun(x+(1e-5))-fun(x-(1e-5)))/(2*1e-5) } der2 <- function(x) { (der(x+(1e-5))-der(x-(1e-5)))/(2*1e-5) } newton <- function(init,niter,error) { i <- 0 dif <- 100 soluz <- init while ((i < niter) & (dif > error)) { print(c(i,soluz,fun(soluz),der(soluz),dif)) soluz_new <- soluz - der(soluz)/der2(soluz) dif <- abs(soluz_new-soluz) i <- i + 1 soluz <- soluz_new } soluz } newton(1,100,1e-6) montec <- function(nsamp,xmin,xmax) { runx <- runif(nsamp)*(xmax-xmin)+xmin soluz <- fun(runx) area <- (mean(soluz))*(xmax-xmin) errore <- sqrt(var(soluz)/nsamp)*(xmax-xmin) c(area,errore) } montec(100000,1,3) nsamp <- 10000 xmin <- 1 xmax <- 3 runx <- runif(nsamp)*(xmax-xmin)+xmin soluz <- log(runx+1)/(runx+1) area <- (mean(soluz))*(xmax-xmin) errore <- sqrt(var(soluz)/nsamp)*(xmax-xmin) c(area,errore)