Home > OS >  Wallis product doesn't produce value of pi
Wallis product doesn't produce value of pi

Time:10-31

I am trying to calculate this product (https://en.wikipedia.org/wiki/Wallis_product) in R but my code doesn't work. Where am I going wrong?

W <- function(n) {
    for (i in 1:n) {
        r <- (2*i/(2*i-1)*2*i/(2*i 1))
    }
    print(r*2)
}

W(10)
W(50)
pi 

CodePudding user response:

You need to make r a running product.

Wallis <- function(n) {
    r <- 1
    for (i in 1:n) {
        r <- r * (2*i/(2*i-1)*2*i/(2*i 1))
    }
    print(r*2)
}

Wallis(500)
#[1] 3.140024

CodePudding user response:

You could avoid the for-loop and use vectorization:

wallis <- function(n) {
  i <- seq_len(n) 
  # Return:
  2 * prod(2 * i / (2 * i - 1) * 2 * i / (2 * i   1))
} 

wallis(500)
#> [1] 3.140024
  •  Tags:  
  • r
  • Related