Quickly determine if vectors are independent

93 Views Asked by At

Just trying to determine if two vectors are independent or dependent. Instead of computing the cross product or dot product, faster to just go element by element and see if the common factor between all the elements is the same (?).

const areIndependent = (a: Array<number>, b: Array<number>) => {

    let firstFactor = math.divide(a[0], b[0]);

    for(let j = 1; j < a.length; j++){
        if(math.divide(a[j],b[j]) !== firstFactor){
            return true;
        }
    }

    return false;
}

the above should work, but I realized that dividing by zero will be a problem. If the denominator is zero, how do I handle this properly? Not sure.

1

There are 1 best solutions below

3
On BEST ANSWER

I think the code is OK as is. But we can add stuff to be more explicit:

const areIndependent = (a: Array<number>, b: Array<number>) : Boolean => {

    if(a[0] !== 0 && b[0] === 0){
        // if one elem is 0 and the other is not, then they always LI
        return true;
    }

    if(a[0] === 0 && b[0] !== 0){
        return true;
    }

    const firstFactor = math.divide(a[0],b[0]);

    for(let j = 1; j < a.length; j++){

        if(a[j] === 0 && b[j] !== 0){
            return true;
        }

        if(a[j] !== 0 && b[j] === 0){
            return true;
        }

        const currFactor = math.divide(a[j], b[j]);
        if(!math.equal(currFactor,firstFactor)){
            return true;
        }
    }
    return false;
}

this should be a lot faster than the cross product or dot product if you just want to find out if two vectors are linearly independent.