python code for parallel vectors

4.1k Views Asked by At

Wrote some Python code to verify if my Vectors are parallel and/or orthogonal. Parallel seems to be alright, orthogonal however misses out in one case. I thought that if the dotproduct of two vectors == 0, the vectors are orthogonal? Can someone tell me what's wrong with my code?

def isParallel(self,v):
    try:
        print self.findTheta(v,1)
        if (self.findTheta(v,1) == 0 or self.findTheta(v,1) == 180):
            return True
    except ZeroDivisionError:
        return True

    return False

def isOrthogonal(self,v):
    print self.dotProduct(v)
    if self.dotProduct(v) == 0:
        return True

    return False

def dotProduct(self,v):
    dotproduct = sum([self.coordinates[i]*v.coordinates[i] for i in range(len(self.coordinates))])
    return dotproduct
2

There are 2 best solutions below

0
On BEST ANSWER
def isOrthogonal(self,v,tolerance=1e-10):
    if abs(self.dotProduct(v)) < tolerance:
        return True

    return False

the above code runs fine, as there are chances of rounding errors in my original code. Hans Lundmark got is straight: floating point rounding errors can cause the code to falter and produce false negatives.

0
On

If you're working with 3D vectors, you can do this concisely using the toolbelt vg. It's a light layer on top of numpy and it supports single values and stacked vectors.

import numpy as np
import vg

v1 = np.array([1.0, 2.0, 3.0])
v2 = np.array([-2.0, -4.0, -6.0])

vg.almost_collinear(v1, v2)
# True

I created the library at my last startup, where it was motivated by uses like this: simple ideas which are verbose or opaque in NumPy.