finding a set of three mutually perpendicular vectors.

D1189cc75544eea31979c55b45fa72ef
0
broli86 101 Aug 08, 2008 at 15:12

Hello, I just came across a code that can find a set of three mutually orthogonal vectors U,V,N such that U X V = N when only one vector N is known. Can some one please tell me how this is working ? Why does he compare x and y coordinates ?

void compute_orthogonal_set(vector *U, vector *V, vector *N)
{
    double invlength;
    
    if (fabs(N->x) >= fabs(N->y))
    {
        invlength = 1 / sqrt(N->x * N->x + N->z * N->z);
        U->x = -N->z * invlength;
        U->y = 0;
        U->z = N->x * invlength;
        V->x = N->y * U->z;
        V->y = N->z * U->x - N->x * U->z;
        V->z = -N->y * U->x;
    }
    else
    {
        invlength = 1 / sqrt(N->y * N->y + N->z * N->z);
        U->x = 0;
        U->y = N->z * invlength;
        U->z = -N->y * invlength;
        V->x = N->y * U->z - N->z * U->y;
        V->y = -N->x * U->z;
        V->z = N->x * U->y;
    } 
}

1 Reply

Please log in or register to post a reply.

A8433b04cb41dd57113740b779f61acb
0
Reedbeta 167 Aug 08, 2008 at 16:49

If you look at the code in the first branch of the if, what it is doing is first calculating U by finding a vector in the XZ plane that is perpendicular to N, and then calculating V = N x U. In the second branch it’s the same thing but using the YZ plane instead.

You have to have both alternatives because in the first branch if N = (0, 1, 0) then the code will fail (the sqrt will be zero and invlength will be infinite). In the second case it will fail if N = (1, 0, 0). Comparing the X and Y coordinates as it does is probably for numerical stability - it will reduce roundoff error.

There’s nothing special about using the XZ and YZ planes - you could write equivalent code using any two of the three axis planes (XY, XZ, and YZ).