简体   繁体   中英

Using Monte Carlo for computing circle area

I am trying to write a function circle_MC that takes the length of radius and the number of simulations (N) as an input and returns the area enclosed by a circle.

For doing that, I create a numeric vector and change it to "1", if the point is inside the circle, ie the ifelse statement holds. My code so far:

circle_MC <- function(r, N)
{
  inside <- numeric(N),#only zeroes
  
  x_sim[i] <-  runif(N, min = -r, max = r),
  y_sim[i] <-  runif(N, min = -r, max = r),
  inside <- ifelse(x_sim^2[i] + y_sim^2[i] <= r, 1, 0),
  area <- (sum(inside)/length(inside)*4)
  
  return(area)
}

However, it gives me the error message "Error: unexpected '}' in "}".

I am pretty new to R and would love to understand where my mistake is.

THe issue is with the , at the end of each assignment. Here, each assignment is a separate statement. It is not clear where the i comes from as the arguments are only 'r' and 'N'

circle_MC <- function(r, N)
{
  inside <- numeric(N) #only zeroes removed , 
  
  x_sim <-  runif(N, min = -r, max = r) # removed ,
  y_sim <-  runif(N, min = -r, max = r)  # removed ,
  inside <- ifelse(x_sim^2 + y_sim^2 <= r, 1, 0) # removed ,
  area <- (sum(inside)/length(inside)*4)
  
  return(area)
}

You can avoid i as it is not a loop (Updated thanks to @duckmayr):

#Function
circle_MC <- function(r, N)
{
  inside <- numeric(N)#only zeroes
  
  x_sim <-  runif(N, min = -r, max = r)
  y_sim <-  runif(N, min = -r, max = r)
  inside <- ifelse(x_sim^2 + y_sim^2 <= r^2, 1, 0)
  area <- ((sum(inside)/length(inside))*((2*r)^2))
  
  return(area)
}

Output:

#Code
circle_MC(2,100)

[1] 12.8

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM