reject = function(fx, a, b, k) { while (1) { x = runif(1, a, b) y = runif(1, 0, k) if (y < fx(x)) return (x) } } fx = function(x) { if (x <= 0) return (0) if (x >= 2) return (0) if (x < 1) return (x) return (2-x) } # n=5000 # z = rep(0, n) # for (i in 1:n) z[i] = reject(fx, 0, 2, 1) # hist(z, freq=FALSE, ylim=c(0,1.01)) # lines(c(0,1,2),c(0,1,0))