%How to generate uniformly distributed numbers on the unite sphere %Parameters: n-number of random numbers. As some points are rejevted not % the final number of points. % method-the method used % isdisplay-if 0 no picture is given. Used for speed calculation %See: http://mathworld.wolfram.com/SpherePointPicking.html function drawsphere(n,method,isdisplay) if nargin<2 method =1 ; end if nargin<3 isdisplay =1 ; end switch method case 1 disp('Incorrect method, there are too many elements on the pole'); r=rand(n,2); theta=r(:,1)*2*pi; fi=r(:,2)*pi; x=cos(theta).*sin(fi); y=sin(theta).*sin(fi); z=cos(fi); case 2 disp('Corrected method, choice the height uniformly'); r=rand(n,2); theta=r(:,1)*2*pi; fi=acos(2*r(:,2)-1); x=cos(theta).*sin(fi); y=sin(theta).*sin(fi); z=cos(fi); case 3 disp('Corrected method, choice the height uniformly, no arccos'); r=rand(n,2); theta=r(:,1)*2*pi; u=2*r(:,2)-1; x=sqrt(1-u.^2).*cos(theta); y=sqrt(1-u.^2).*sin(theta); z=u; case 4 disp('Marsaglia method'); r=2*rand(n,2)-1; %Try to remove, one will not get a sphere r=r((r(:,1).^2+r(:,2).^2<=1),:); x=2*r(:,1).*sqrt(1-r(:,1).^2-r(:,2).^2); y=2*r(:,2).*sqrt(1-r(:,1).^2-r(:,2).^2); z=1-2*(r(:,1).^2+r(:,2).^2); case 5 disp('von Neumann-Cook method'); r=2*rand(n,4)-1; %Try to remove, one will not get a sphere r=r((r(:,1).^2+r(:,2).^2+r(:,3).^2+r(:,4).^2<=1),:); u=r(:,1).^2+r(:,2).^2+r(:,3).^2+r(:,4).^2; x=2*(r(:,2).*r(:,4)+r(:,1).*r(:,3))./u; y=2*(r(:,3).*r(:,4)-r(:,1).*r(:,2))./u; z=(r(:,1).^2+r(:,4).^2-r(:,2).^2-r(:,3).^2)./u; case 6 disp('Muller-Marsaglia method'); r=randn(n,3); u=sqrt(r(:,1).^2+r(:,2).^2+r(:,3).^2); x=r(:,1)./u; y=r(:,2)./u; z=r(:,3)./u; otherwise disp('Wrong method'); return; end if isdisplay scatter3(x,y,z,'.','g'); [u v w]=sphere; hold on;surf(u,v,w); colormap(copper);hold off; end end