You might also have a look at this Julia snippets: Basics of generating random numbers in Julia (it is Julia 0.6 based but the reasons for the bias have not changed).
Having said that for very small N
in very tight loops I use the approximate formula as the bias is small and it is significantly faster (see the corrected benchmark below - also you have to use 1+floor
not ceil
as ceil
can produce 0
):
julia> f1(N=5,M=10^6) = mean(iseven(1+floor(Int, N*rand())) for i in 1:M)
f1 (generic function with 3 methods)
julia> f2(N=5,M=10^6) = mean(iseven(rand(1:N)) for i in 1:M)
f2 (generic function with 3 methods)
julia> @btime f1()
9.020 ms (0 allocations: 0 bytes)
0.400145
julia> @btime f2()
17.681 ms (0 allocations: 0 bytes)
0.399574