# Random Vectors

Hi,

i need a function, that creates a random vector. As parameters i give it a normal-vector, which would be the standard direction and an int (alpha), which would be the maximum deviation from the normal in degree (so if alpha=180° the vector could point everywhere).
I really can´t think of any good solution.

Thanks.
Jan.

Just FYI, this is more of a math question than an OpenGL question, so you might take some heat from posting here.

Why not just pick a random rotation axis (vector) then use your angle (alpha) and this axis to make a rotation matrix for your original vector? If you need to know how to build such a matrix, use google to look up the man pages for glRotatef( ).

– Zeno

Hi

why not following:

vec normal,random;
float angle;

do
{
vec[0]=rand();
vec[1]=rand();
vec[2]=rand();
}while ( dotproduct(normal,random) <= cos(angle))
normalize(vec);

Bye
ScottManDeath

ScottMan,

That function will generate vectors that cluster towards the corners of a “cube” surrounding the sphere.

You should use the function for an evenly distributed point on the shell of a sphere, and adjust it for only a slice of a sphere, where the slice height is one minus the cosine of the angle you want to use.

vector random_vector(float angle) {
float x = rand_closed(cos(angle),1);
float a = rand_half_open(-PI,PI);
float r = sqrtf(1-x*x);
float y = sin(a)*r;
float z = cos(a)*r;
return vector(x,y,z);
}

Proof that this generates a unit vector:

x = [-1,1]
r = sqrt(1-xx)
y = cos(a)r
z = sin(a)r
x
x+y
y+z
z == 1

yy/rr+zz/rr == 1
yy+zz == rr == 1-xx
yy+zz+x*x == 1

Proof that this generates a uniformly distributed point on the shell of a sphere (or sphere slice) can be derived by looking at the surface covered by each sample in the quantized case for quantization approaching zero, i e through simple integration.