I have the following (unnormalized) probability density function (pdf):

f(x) = -x*(x-1)

whose support is the interval (0, 1). I have coded the following to generate a 10000-element array of random numbers drawn from the pdf above:

f_rand = []
for i in 1:10000
x = rand()
u = 1/4*rand()
f_cand = f(x)
if u < f_cand
push!(f_rand, x)
end
end

which does seem to work (I plotted the corresponding histogram(f_rand) for several trials).
I would like to know whether this is coded is an efficient way or I should do some streamling (âvectorizationâ of the loops, perhaps?).

Also have a look at the performance tips in the manual. For instance you should put your code into a function, profile it with BenchmarkTools, and check with @code_warntype.

I would start with putting the code in a function and make sure that the array youâre pushing into is typed concretely, right now itâs an array of Any.