[R] about loops

baptiste auguie baptiste.auguie at googlemail.com
Thu Jan 21 13:49:18 CET 2010


Hi,

One approach could be a while loop as follows. Note that your circle
should have radius 0.5 if I understood the problem correctly.


N <- 5

npoints <- 0
ntests <- 0
points.in.circle <- matrix(NA, ncol=2, nrow=N)

while (npoints < N) {

  test.point <- runif(2, -0.5, 0.5) # generate new point in 2D
  if ( sqrt(test.point %*% test.point) <= 0.5){ # test its distance to
the origin
    npoints <- npoints + 1
    points.in.circle[npoints, ] <- test.point
  }
  ntests <- ntests + 1
}

print(paste(npoints, "out of", ntests, 'where in the circle') )

HTH,

baptiste


2010/1/21 Wolfgang Amadeus <fdfcz123 at 163.com>:
> Hello !
>  I have a quick question about loops.
>  For example,  I have a 1 * 1 square and its inscribed circle tangent i, whose radius, of course, is also 1.
>  The loop here is as the following:
>  generate n points, say 5, in the square randomly repeatedly until we have five in total in the circle, then we stop, otherwise we continue.
>  I do not know how !
> Help me Please ~
> Thank you very much for your time.
>  Yours
> Wolfgang Amadeus
>
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list