[R] Integrating a function that contains for loop or vectorization for for loop

Rui Barradas ru|pb@rr@d@@ @end|ng |rom @@po@pt
Sun Jul 19 22:19:30 CEST 2020


Hello,

The functions are not equivalent.
integrate subdivides the interval lower = 0, upper = 10 in into a 
maximum subdivisions = 100L. If you print length(X) you will see that 
it's 21.
X is a vector of 21 values and to compute X^(1:10) this expands to

X[1]^1, X[2]^2, ..., X[10]^10, X[11]^1, X[12]^2, ..., X[20]^10, X[21]^1

Each of these values is multiplied by a*b and then added.
A total different computation is performed by the second function:

X[1:21]^1, X[1:21]^2, etc.

I have rewrote the functions a bit, without the print statements and in 
myfun2 creating the list term beforehand.



myfun <- function(X, a, b){
   k <- 1:10
   term <- a * b * X^k
   fx <- exp(X) * sum(term)
   fx
}

myfun2 <- function(X, a, b){
   term <- vector("list", length = 10)
   for(k in 1:10){
     term[[k]] <- a * b * X^k
   }
   fx <- exp(X) * sum(unlist(term))
   fx
}

a <- 5
b <- 4

integrate(myfun, lower = 0, upper = 10, a = a, b = b)
integrate(myfun2, lower = 0, upper = 10, a = a, b = b)

curve(myfun(x, a = a, b = b), 0, 10)
curve(myfun2(x, a = a, b = b), 0, 10, col = "blue", add = TRUE)

Hope this helps,

Rui Barradas

Às 04:14 de 18/07/2020, Shaami escreveu:
> Hi Everyone
>
> It has been a long time I am facing a problem with integrating a function
> that contains for-loop or even vectorization of for loop. Could you please
> guide for the following MWE that how I could get rid of the error or
> warning messages?
>
> My MWE code is here:
>
> myfun <- function(X, a, b){
>    k <- 1:10
>    term <- a * b * X^k
>    fx <- exp(X) * sum(term)
>    print(X)
>    print(term)
>    return(fx)
> }
>
> a <- 5
> b <- 4
> integrate(myfun, lower = 0, upper = 10, a = a, b = b)
>
> If I use the following version of my code, it does not give any error.
> However, I am not sure that it is correct.
>
> myfun <- function(X, a, b){
>    term <- list()
>    for(k in 1:10){
>      term[[k]] <- a * b * X^k
>    }
>    fx <- exp(X) * sum(unlist(term))
>    print(X)
>    print(term)
>    return(fx)
> }
>
> a <- 5
> b <- 4
> integrate(myfun, lower = 0, upper = 10, a = a, b = b)
>
>
>
> Thank you
>
> Regrads
>
> 	[[alternative HTML version deleted]]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.

-- 
Este e-mail foi verificado em termos de vírus pelo software antivírus Avast.
https://www.avast.com/antivirus



More information about the R-help mailing list