Calculate Pi in R

R has a built in function for pi but for pi day (3/14) I thought it would be fun to program R to calculate pi. I found a formula called Nilicantha’s formula:

# pi = 3 + 4/(2*3*4) – 4/(4*5*6) + 4/(6*7*8) – 4/(8*9*10) + 4/(10*11*12) – (4/(12*13*14) …

Here’s the code I wrote:

options(digits = 22) # 22 is max allowed
pi_calc <- 3
x <- 2
n <- 10000
for(i in 1:n) {
y <- x + 1
z <- x + 2
combine_with_pi_calc <- 4 / (x * y * z)
test <- i %% 2 == 0 
if (isTRUE(test)) {
 pi_calc <- pi_calc - combine_with_pi_calc
}
else {
 pi_calc <- pi_calc + combine_with_pi_calc
}
x <- z
print(pi_calc)
}
# Compare to the pi constant included in R
# Matches out to the 12th digit
# I think the error is due to floating point, not the formula, but I'm not sure.
print(pi)

It works!

[1] 3.141592653589537764702
[1] 3.141592653590038697331
[1] 3.141592653589537764702
[1] 3.141592653590038253242
[1] 3.141592653589537764702
[1] 3.141592653590038253242
[1] 3.141592653589538208792
[1] 3.141592653590038253242
[1] 3.141592653589538208792
> 
> # Compare to the pi constant included in R
> # Matches out to the 12th digit
> print(pi)
[1] 3.141592653589793115998

What do you think? Has anyone else written code to calculate pi in R?

2 thoughts on “Calculate Pi in R

    1. Justin@RProgramming.net Post author

      Nice article except for the part where you used SAS instead of R. 🙂 Thanks for sharing!

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *