我不知道为什么下面的代码没有给我完整的圆圈,只给出了部分内容.另外,我不知道如何在一个正方形内的圆圈或外面显示我的点,这两个点都以(0,0)为中心,r = 1,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)
Run Code Online (Sandbox Code Playgroud)
这是输出
所以我把它固定到下面,当我得到100分时,图表看起来如下.为什么没有显示完整的圆圈?
plot(x,y)
draw.circle(0,0,1,nv=1000,border=NULL,col=NA,lty=1,lwd=1)
Run Code Online (Sandbox Code Playgroud)

所以多亏了费尔南多,我修复了这个情节,现在它看起来像这样,但我希望它的范围从(-1到1)为x,就像是y一样.xlim没用.你知道什么是错的吗?
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)
}
}
Run Code Online (Sandbox Code Playgroud)
并调用以下函数:
monte.carlo.pi(100,T)
Run Code Online (Sandbox Code Playgroud)
目前的情节如下:

Gre*_*gor 24
如果你想让圆圈看起来像一个圆圈给用户,费尔南多的答案是好的.这个答案涵盖了在数据维度中绘制一个圆.
如果您的x和y轴缩放相同,例如,如果将宽高比设置为1(asp = 1),则这两种方法是等效的.
# initialize a plot
plot(c(-1, 1), c(-1, 1), type = "n")
# prepare "circle data"
radius <- 1
theta <- seq(0, 2 * pi, length = 200)
# draw the circle
lines(x = radius * cos(theta), y = radius * sin(theta))
Run Code Online (Sandbox Code Playgroud)
Fer*_*ndo 17
您需要指定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)
Run Code Online (Sandbox Code Playgroud)

编辑:只是旁注,您可以使您的蒙特卡洛功能更有效:
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
}
Run Code Online (Sandbox Code Playgroud)