Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ## Julia 0.6
- ## https://news.ycombinator.com/item?id=17688599
- ## https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/
- function vec4(n)
- out = Matrix{Float64}(3,n)
- @inbounds for i=1:n
- θ = 2π*rand()
- cϕ = 2*rand()-1 ## don't write ϕ = acos(cϕ)...
- sϕ = sqrt(1-cϕ^2)
- r = cbrt(rand())
- out[1,i] = r * sϕ * cos(θ)
- out[2,i] = r * sϕ * sin(θ)
- out[3,i] = r * cϕ
- end
- out
- end
- function vec1(n)
- out = Matrix{Float64}(3,n)
- rr = ones(3)
- i=0
- @inbounds while i<n
- rand!(rr)
- scale!(rr,2)
- rr .-= 1
- if sum(abs2,rr)<=1
- i+=1
- out[:,i] .= rr
- end
- end
- out
- end
- using BenchmarkTools
- @btime vec1(10^7) ## 1.470 s
- @btime vec4(10^7) ## 967.866 ms
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement