On 18-Jun-10 18:18:41, Ron Michael wrote: > Thank you so much Teds for pviding this function. Would you please > explain the theory behind that? > _ > Thanks,
[A] Sampling uniformly on the circumference of the circle: This one is simple. Given that you are sampling uniformly on the cirumference, the position is determined by the angular distance around the circle fron 0 to 2*pi, and this has to be uniformly distributed. Hence u=2*pi*runif() is a uniformly distributed angle from 0 to 2*pi. You then need to find the (x,y) coordinates of such a point on a circle of radius "rad" centred at c(x0,y0), which are x = rad*cos(u) + x0, y = rad*sin(u) + y0. Hence: csamp <- function(n,rad=1,centre=c(0,0)){ x0 <- centre[1] ; y0 <- centre[2] u <- 2*pi*runif(n) cbind(x=rad*cos(u)+x0, y=rad*sin(u)+y0) } [B] Sampling uniformaly within the circle Here, consider first sampling uniformly on the thin circular domain between radius r and radius (r + rd). For small dr, we are in effect in situation [A]; hence, given r, the angular distances will again be uniformly distributed, so you again use u = 2*pi*runif(n). However, the area of this circular domain is pi*(r + dr)^2 - pi*r^2 = 2*pi*r*dr [ + dr^2 which we neglect]. So the proportion of the points expected to fall between r and r+dr is proportional to r*dr, i.e. the probability density of r is proportional to r. Hence, for unrestricted values of R, Prob[ a point at distance <= r from centre ] is proportional to r^2, and (for an enclosing circle of unit radius) must be equal to 1 for r=1. Hence Prob[ a point at distance <= r from centre ] = r^2 This is the cumulative distribution function of the random r, and therefore r^2 is uniformly distributed: for any random variable X, let F(x) = Prob[ X <= x ]. Then U = F(X) is random, and Prob[ U <= u ] = Prob[ F(X) <= u ] = Prob[ X <= Finv(u) ] = F( Finv(u) ) = u where Finv is the inverse function of F [F(x) = u ; u = Finv(x)]. Hence U is uniformly distributed. But, for r, U = F(r) = r^2, so r = sqrt(U) where U is uniformly distributed (as above). Hence the line r <- sqrt(runif(n)) in the following [the rest being basically the same as in [A], except that r is now random so we have the extra factor r in cbind(x=rad*r*cos(u)+x0, y=rad*r*sin(u)+y0) ] Csamp <- function(n,rad=1,centre=c(0,0)){ x0 <- centre[1] ; y0 <- centre[2] u <- 2*pi*runif(n) r <- sqrt(runif(n)) cbind(x=rad*r*cos(u)+x0, y=rad*r*sin(u)+y0) Hoping this helps, Ted. -------------------------------------------------------------------- E-Mail: (Ted Harding) <ted.hard...@manchester.ac.uk> Fax-to-email: +44 (0)870 094 0861 Date: 18-Jun-10 Time: 21:01:17 ------------------------------ XFMail ------------------------------ ______________________________________________ R-help@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.