Generating uniformly random distribution of points inside a sphere

Average rating
(0 votes)

This code generates uniform random points within a sphere. The sphere is centred at the origin with a variable radius. The generation is by direct calculation, rather than by exclusion. I found many examples for this in python, mathematica etc. but none for Igor. Hopefully it's useful for somebody.

////	@param	num		number of points to be generated
////	@param	Radius	radius of sphere
Function UniformSphere(num,Radius)
	Variable num,Radius
	Make/O/N=(num) xw,yw,zw
	Variable phi,theta,rr
	Variable i
	for(i = 0; i < num; i += 1)
		phi = pi + enoise(pi)
		theta = acos(enoise(1))
		rr = Radius * ((0.5 + enoise(0.5))^(1/3))
		xw[i] = rr * sin(theta) * cos(phi)
		yw[i] = rr * sin(theta) * sin(phi)
		zw[i] = rr * cos(theta)
	DoWindow/K xyPlot
	Display/N=xyPlot yw vs xw
	ModifyGraph/W=xyPlot mode=3,marker=8
	ModifyGraph/W=xyPlot width={Plan,1,bottom,left}
	DoWindow/K yzPlot
	Display/N=yzPlot zw vs yw
	ModifyGraph/W=yzPlot mode=3,marker=8
	ModifyGraph/W=yzPlot width={Plan,1,bottom,left}
	DoWindow/K xzPlot
	Display/N=xzPlot zw vs xw
	ModifyGraph/W=xzPlot mode=3,marker=8
	ModifyGraph/W=xzPlot width={Plan,1,bottom,left}

It might be useful to add

It might be useful to add the following (requires IP7)

JointHistogram xw,yw,zw

Also, to visualize the distribution why not display it in Gizmo:

Concatenate {xw,yw,zw},triplet
AppendToGizmo defaultScatter=triplet

Depending on the number of points you may want to either display them as a cloud or simply reduce the radius:

ModifyGizmo ModifyObject=scatter0,objectType=scatter,property={ size,0.2}

Back to top