How to write a function to generate a sequence of points in R? -
this pdf dealing with:
fx = 0.3 if (0<=x<1) 0.1 if (1<=x<2) 0.25 if (2<=x<3) 0.15 if (3<=x<4) 0.2 if (4<=x<5) 0 otherwise
i have write function gen_xy generate sequence of points (x, y) uniformly distributed in (0, 5) x (0, 0.5) until 1 lies in region under curve of y = fx(x)
.
this code far:
fx <- function(x) c(0, 0.3,0.1,0.25,0.15,0.20, 0) [findinterval(x, c(-inf, 0:5, inf))] x <- runif(n,0,5) fx <- stepfun(x = 0:5, y = c(0,0.3,0.1,0.25,0.15,0.20,0)) plot(fx, ylim = c(0,0.5),xlim = c(0,5), main = 'f(x)')
now attempt @ writing code function:
gen_xy <- function() { done=0 while(done==0) { x=runif(1,0,5) y=runif(1,0,0.5) print(c("x,y",c(x,y))) if(y < fx(x)) { done=1 } } xy=c(x,y) xy }
but think part if(y < fx)
wrong?
i need generate sample of 1000 points , plot them check if appropriate sample under curve of y=fx
. how go writing such code?
your gen_xy()
function understand want ... generates sequence of points, until 1 lies under line ... , breaks out of loop. tried , generated couple of points ... ... add them plot if ad points(x,y,col="red")
or loop.
to genrate 1000 points like:
x=runif(1000,0,5) y=runif(1000,0,0.5)
this can put on plot points(x,y)
but not sure mean appropriate sample. ??
you can compare generated points against curve again:
y < fx(x)
and subset them doing x[y < fx(x)] , y[y < fx(x)].
Comments
Post a Comment