简体   繁体   中英

How to write a function to generate a sequence of points in R?

This is the PDF that I am 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 to write a function gen_xy that will generate a sequence of points (X, Y) uniformly distributed in (0, 5) X (0, 0.5) until one lies in the region under the curve of y = fx(x) .

This is my code so 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 this is my attempt at writing the code for my 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 I think the part if(y < fx) is wrong?

I then need to generate a sample of 1000 points and plot them to check if they are an appropriate sample from under the curve of y=fx . How would I go about writing such a code?

your gen_xy() function does what I understand you want it to do ... generates a sequence of points, until one lies under the line ... and then breaks out of the loop. I tried it and usually it generated just a couple of points ... ... you could add them to your plot if you ad points(x,y,col="red") or something like this into your loop.

To genrate 1000 points you would do something like:

     x=runif(1000,0,5)
     y=runif(1000,0,0.5)

This you can then put on your plot with points(x,y)

But I am not sure what you mean with appropriate sample. ??

You can compare the generated points against the curve again:

     y < fx(x)

and subset them doing x[y < fx(x)] and y[y < fx(x)].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM