Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scatter randomly points on a sphere


using PyPlot
n = 50
u = range(0,stop=2*π,length=n);
v = range(0,stop=π,length=n);

x = cos.(u) * sin.(v)';
y = sin.(u) * sin.(v)';
z = ones(n) * cos.(v)';

scatter3D(vec(x),vec(y),vec(z);c="red",s=1)

enter image description here

However, if I multiply vec(x), vec(y), vec(z) with rand() ,
I still get the same plot with the only difference being that the axis change or in other words that the sphere gets "squished".


using PyPlot
n = 50
u = range(0,stop=2*π,length=n);
v = range(0,stop=π,length=n);

x = cos.(u) * sin.(v)';
y = sin.(u) * sin.(v)';
z = ones(n) * cos.(v)';

scatter3D(rand()*vec(x),rand()*vec(y),rand()*vec(z);c="red",s=1)

enter image description here

like image 989
Struggling_Student Avatar asked Jun 22 '21 08:06

Struggling_Student


1 Answers

The simplest approach seems to be sampling a Gaussian for each dimension and then normalizing the length of the resulting vector as described in this answer. There's a very slight possibility of getting a vector with zero length, which can be handled with rejection sampling. Putting that together you would do this:

points = map(1:n) do _
   while true
       x = randn()
       y = randn()
       z = randn()
       l = hypot(x, y, z)
       l ≠ 0 && return (x, y, z) ./ l
    end
end

This gives a vector of 3-tuples each representing x, y and z coordinates of points, which you can plot as before. Separate vectors of coordinates can be extracted using comprehensions:

xs = [p[1] for p in points]
ys = [p[2] for p in points]
zs = [p[3] for p in points]

This approach can readily be generalized to any number of dimensions.

like image 186
StefanKarpinski Avatar answered Oct 19 '22 23:10

StefanKarpinski