簡體   English   中英

R 相當於 scipy.integrate.simps()?

[英]R equivalent to scipy.integrate.simps()?

我希望對一個函數進行一些數值積分,在該函數中我只有來自該函數的樣本,並且無法生成任意的新樣本。 我知道在 python 世界中,這可以通過 scipy.integrate.simps() 實現,但我的工作流程目前在 R 中。關於 R 函數/包的任何建議來實現這一點?

假設你有一個 x 值向量和一個 y 值向量,你可以很容易地應用辛普森規則。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM