Mona Jalal - 11 months ago 58

R Question

I don't know why the following code doesn't give me the complete circle and gives only parts of it. Also I don't know how I can show my points on the circle or outside of it within a square both centered at (0,0) with r=1 and a=2.

`library("plotrix")`

n<-1000

plot.new()

frame()

x<-runif(n,-1,1)

y<-runif(n,-1,1)

for (i in 1:n) { plot(x[i],y[i])}

draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)

Here's the output

So I fixed it to the following and when I have 100 points the graph looks the following. Why the complete circle isn't shown?

`plot(x,y)`

draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)

So thanks to Fernando I fixed the plot and now it looks like this but I want it to have range from (-1 to 1) for x like it is for y. xlim didn't work. Do you know what's wrong?

`magnitude = function(x, y) {`

stopifnot(isTRUE(all.equal(length(x),length(y))))

return (sqrt(x^2 + y^2))

}

library("plotrix")

monte.carlo.pi<-function(n,draw=FALSE)

{

circle.points<-0

square.points<-0

x<-runif(n,-1,1)

y<-runif(n,-1,1)

for (i in 1:n)

{

#if ((x[i])^2 + (y[i])^2 <=1)

if (magnitude(x[i],y[i])<=1)

{

circle.points<-circle.points+1

square.points<-square.points+1

} else

{

square.points<-square.points+1

}

}

if (draw==TRUE)

{

plot.new()

frame()

plot(x,y,asp=1,xlim=c(-1,1),ylim=c(-1,1))

draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)

rect(-1,-1,1,1)

return(4*circle.points / square.points)

}

}

and call the function like the following:

`monte.carlo.pi(100,T)`

current plot is like following:

Answer

You need to specify `asp = 1`

:

```
x = runif(100, -1, 1)
y = runif(100, -1, 1)
plot(x, y, asp = 1, xlim = c(-1, 1))
draw.circle(0, 0, 1, nv = 1000, border = NULL, col = NA, lty = 1, lwd = 1)
```

EDIT: Just a side note, you can make your Monte Carlo function more efficient:

```
mc.pi = function(n) {
x = runif(n, -1, 1)
y = runif(n, -1, 1)
pin = sum(ifelse(sqrt(x^2 + y^2 <= 1), 1, 0))
4 * pin/n
}
```

Source (Stackoverflow)