[R] r-ish ? how can i improve my code?
Philipp Pagel
p.pagel at gsf.de
Wed Oct 15 11:58:56 CEST 2003
On Wed, Oct 15, 2003 at 10:06:36AM +0100, Sean O'Riordain wrote:
> n <- 900; # number of valid items required...
>
> x <- numeric(n);
> y <- numeric(n);
> z <- numeric(n);
>
> c <- 1; # current 'array' pointer
> tc <- 0; # total items actually looked at...
>
> while (c <= n) {
> x[c] = runif(1, 0, 1);
> y[c] = runif(1, 0, 1);
>
> z[c] = sqrt(x[c]^2 + y[c]^2);
> if (z[c] < 1)
> c <- c + 1;
> tc <- tc + 1;
> }
>
> print("'overwork' ratio");
> print(tc/(c-1));
> plot(x,y);
If I read this correctly you want to find the frequency of the event
"sqrt(x^2 + y^2) < 1" where 0 <= x, y <= 1
right?
How about this:
n <- 1000
z <- sqrt(runif(n,0,1)^2 + runif(n,0,1)^2)
ratio <- (length(z)-1) / (length( z[z<1] ))
The main difference of course is that I uses a fixed number of "total
items" rather than "valid items". If that's a problem and you need
exactly 900 "valid items" things get a bit more complicated...
cu
Philipp
--
Dr. Philipp Pagel Tel. +49-89-3187-3675
Institute for Bioinformatics / MIPS Fax. +49-89-3187-3585
GSF - National Research Center for Environment and Health
Ingolstaedter Landstrasse 1
85764 Neuherberg, Germany
More information about the R-help
mailing list