Search code examples
pythonrscipynumerical-methodsintegral

R equivalent to scipy.integrate.simps()?


I'm looking to do some numeric integration on a function where I only have samples from the function, and can't generate arbitrary new samples. I understand that over in the python universe this is can be achieved via scipy.integrate.simps(), but my workflow is currently in R. Any suggestions on R functions/packages to achieve this?


Solution

  • Assuming you have a vector of x-values and a vector of y-values, you can apply Simpson's rule fairly easily.

    simpson <- function(x, y)
    {
        if(length(x) < 5)
            stop("Must have at least 5 values")
        if(length(x) %% 2 == 0)
            stop("Number of values must be odd")
        ord <- order(x)
        x <- x[ord]
        y <- y[ord]
        diffs <- diff(x)
        delta <- mean(diffs)
        if((max(diffs) - min(diffs))/delta > 1e-6)
            stop("X-values must be equally spaced")
        coefs <- c(1, 4, rep(c(2, 4), (length(x) - 3)/2), 1)
        sum(coefs*y)*delta/3
    }
    
    simpson(1:7, (1:7)^2
    # [1] 114