Reputation: 47
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, i.e. 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.
Upvotes: 2
Views: 202
Reputation: 39585
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
Upvotes: 1
Reputation: 886928
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)
}
Upvotes: 1