What is a formula to get a vector perpendicular to another vector?

Calculate the cross product AxC with another vector C which is not collinear with A.

There are many possible directions in the plane perpendicular to A. If you don't really care, which one to pick, just create an arbitrary vector C not collinear with A:

if (A2 != 0 || A3 != 0)
    C = (1, 0, 0);
else
    C = (0, 1, 0);
B = A x C; 

If the two vectors are perpendicular then their dot product is zero.

So: v1(x1, y1, z1), v2(x2, y2, z2).

=> x1 * x2 + y1 * y2 + z1 * z2 = 0

You know (x1, y1, z1). Put arbitrary x2 andy2 and you will receive the corresponding z2:

z1 * z2 = -x1 * x2 - y1 * y2
=> z2 = (-x1 * x2 - y1 * y2) / z1

Be aware if z1 is 0. Then you are in the plane.


function (a,b,c)
{
    return (-b,a,0)
}

But this answer is not numerical stable when a,b are close to 0.

To avoid that case, use:

function (a,b,c) 
{
    return  c<a  ? (b,-a,0) : (0,-c,b) 
}

The above answer is numerical stable, because in case c < a then max(a,b) = max(a,b,c), then vector(b,-a,0).length() > max(a,b) = max(a,b,c) , and since max(a,b,c) should not be close to zero, so is the vector. The c > a case is similar.