How do I know if two vectors are near parallel
-
30-01-2021 - |
Pergunta
I am having some trouble finding parallel vectors because of floating point precision. How can I determine if the vectors are parallel with some tolerance?
I also need a check for orthogonality with tolerance.
Solução
For vectors v1
and v2
check if they are orthogonal by
abs(scalar_product(v1,v2)/(length(v1)*length(v2))) < epsilon
where epsilon
is small enough. Analoguously you can use
scalar_product(v1,v2)/(length(v1)*length(v2)) > 1 - epsilon
for parallelity test and
scalar_product(v1,v2)/(length(v1)*length(v2)) < -1 + epsilon
for anti-parallelity.
Outras dicas
If you have 3D vectors the answer is simple. Compute the cross product and if it is nearly zero, your vectors are nearly parallel: http://mathworld.wolfram.com/ParallelVectors.html
For 2d vectors you can convert them into 3D vectors just by adding a coordinate with zero (1;2) => (1;2;0), (4; 5.6) => (4; 5.6; 0) and so on
Two vectors are orthogonal or perpendicular, if there dot product ist zero:
http://mathworld.wolfram.com/CrossProduct.html
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.