简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM