0

I want to add a loop to the code below so that it runs four times for

n <- c(1000, 10000, 100000, 1000000)

And to return a matrix that contains n values and its solution pi? Thanks!

Here is my code for a single value of n:

n <- 1000
x <- c(runif(n, -1,1))
y <-c(runif(n, -1,1))
points <- data.frame(cbind(x,y))

z <- points$x^2 + points$y^2
pi <- function(n,points){
  y <- 4*length(z[z<=1])/n
  return(y)
}
pi(n, points)
Cettt
  • 11,460
  • 7
  • 35
  • 58
  • just add `for (n in c(1000, 10000, 100000, 1000000)) {` and close the curly bracket at the end. – Cettt Apr 03 '19 at 12:34
  • @Cettt thanks but it only shows the last run as output, and I'd like to see a matrix(4x2), 2 columns n and pi – discoveries Apr 03 '19 at 12:40

1 Answers1

2

here is a way where you use an implicit loop (sapply) instead of a for loop:

calc_pi <- function(n){
  x <- c(runif(n, -1,1))
  y <-c(runif(n, -1,1))
  points <- data.frame(cbind(x,y))

  z <- points$x^2 + points$y^2
  pi <- function(n,points){
    y <- 4*length(z[z<=1])/n
    return(y)
  }
  pi(n, points)
}

n <- c(1000, 10000, 100000, 1000000)
set.seed(1)
data.frame(n = n, pi = sapply(n, calc_pi))
      n       pi
1 1e+03 3.080000
2 1e+04 3.141600
3 1e+05 3.137640
4 1e+06 3.143064

Note that it is good practice to set a random seed with set.seed when working with random numbers (see e.g. this question).

Cettt
  • 11,460
  • 7
  • 35
  • 58
  • Thanks. If I use set, I would lose the randomness of the output everytime I run the code, or in other words, with set.seed I get the same answer each time I run the code – discoveries Apr 03 '19 at 12:54
  • exactly. But this makes your results reproducible – Cettt Apr 03 '19 at 12:55