# integrateit() -- simple naive one-dimensional R integration function # by Jeffrey S. Rosenthal (www.probability.ca) # Can integrate functions which are not "vectorised" for integrate() integrateit = function(ff, themin=0, themax=1, N=1000) { if (themin >= themax) stop("Error: themin must be smaller than themax") xlist = themin + (0:N)*(themax-themin) / N thesum = 0.0 for (i in 1:(N+1)) thesum = thesum + ff(xlist[i]) return( thesum * (themax-themin) / N ) } # EXAMPLE: f = function(x) { if (x<1/2) return(x^2) else return(x^3) } integrate(f,0,1) # Gives error! integrateit(f) integrateit(f,0,1) integrateit(f,-2,5) integrateit(f,-2,5,10000)