Advertisement
Guest User

uniform points in a 3-ball, Julia

a guest
Aug 5th, 2018
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Julia 0.83 KB | None | 0 0
  1. ## Julia 0.6
  2. ## https://news.ycombinator.com/item?id=17688599
  3. ## https://karthikkaranth.me/blog/generating-random-points-in-a-sphere/
  4.  
  5. function vec4(n)
  6.     out = Matrix{Float64}(3,n)      
  7.     @inbounds for i=1:n
  8.         θ = 2π*rand()
  9.         cϕ = 2*rand()-1  ## don't write ϕ = acos(cϕ)...
  10.         sϕ = sqrt(1-cϕ^2)
  11.         r = cbrt(rand())
  12.         out[1,i] = r ** cos(θ)
  13.         out[2,i] = r ** sin(θ)
  14.         out[3,i] = r *
  15.     end
  16.     out
  17. end
  18.  
  19. function vec1(n)
  20.     out = Matrix{Float64}(3,n)
  21.     rr = ones(3)
  22.     i=0
  23.     @inbounds while i<n
  24.         rand!(rr)
  25.         scale!(rr,2)
  26.         rr .-= 1
  27.         if sum(abs2,rr)<=1
  28.             i+=1
  29.             out[:,i] .= rr
  30.         end
  31.     end
  32.     out
  33. end
  34.  
  35. using BenchmarkTools
  36.  
  37. @btime vec1(10^7) ## 1.470 s
  38. @btime vec4(10^7) ## 967.866 ms
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement