簡體   English   中英

嵌套在R中的for循環-最終結果的問題

[英]Nested for loops in R - Issue with final result

當只知道分布的矩時,我正在解決一個重建(或恢復)概率分布函數的問題。 我已經用R編寫了代碼,盡管邏輯對我來說似乎很正確,但是我沒有得到想要的輸出。

我嘗試使用的方程式是CDF的近似值(重構或恢復的),如下圖所示。 我正在為方程式的右側編寫代碼,並將其等同於我在代碼中稱為F的向量。

包含原始方程式的論文鏈接可以在這里找到。

在本文中將其標記為方程式(2)。

這是我寫的代碼:

#R Codes:  
alpha <- 50
T <- 1
x <- seq(0, T, by = 0.1)

# Original CDF equation
Ft <- (1-log(x^3))*(x^3)  
plot(x, Ft, type = "l", ylab = "", xlab = "")

# Approximated CDF equation using Moment type reconstruction
k<- floor(alpha*y/T)  
for(i in 1:length(k))  
{
for(j in k[i]:alpha)  
{  
F[x+1] <- (factorial(alpha)/(factorial(alpha-j)*factorial(j-k)*factorial(k)))*(((-1)^(j-k))/(T^j))*((9/(j+3))^2)
}
}
plot(x[1:7], F, type = "l", ylab = "", xlab = "")

這里將提供任何幫助,因為使用我的代碼獲得的逼近度和圖形與原始曲線完全不同。

顯然您的問題在這里。

F[x+1] <- (factorial(alpha)/(factorial(alpha-j)*factorial(j-k)*factorial(k)))*(((-1)^(j-k))/(T^j))*((9/(j+3))^2)

您正在嘗試讓x值有所不同,是嗎? 那么,如果等式的右側在x中沒有變化,而左側具有使用非整數索引的賦值,您將如何獲得呢?

    alpha <- 30  #In the exemple you try to reproduce, they use an alpha of 30 if i understood correctly (i'm a paleontologist not a mathematician so this paper's way beyond my area of expertise :) )

    tau <- 1  #tau is your T (i changed it to avoid confusion with TRUE)
    x <- seq(0, tau, by = 0.001)
    f<-rep(0,length(x))  #This is your F (same reason as above for the change). 
    #It has to be created as a vector of 0 before your loop since the whole idea of the loop is that you want to proceed by incrementation.

    #You want a value of f for each of your element of x so here is your first loop:
    for(i in 1:length(x)){

    #Then you want the sum for all k going from 1 to alpha*x[i]/tau:
        for(k in 1:floor(alpha*x[i]/tau)){

    #And inside that sum, the sum for all j going from k to alpha:
            for(j in k:alpha){

    #This sum needs to be incremented (hence f[i] on both side)
                f[i]<-f[i]+(factorial(alpha)/(factorial(alpha-j)*factorial(j-k)*factorial(k)))*(((-1)^(j-k))/(tau^j))*(9/(j+3)^2)
                }
            }
        }

    plot(x, f, type = "l", ylab = "", xlab = "")

暫無
暫無

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

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