## best way to check if 2 vectors are parallel

Need help, or want to share a macro? Post here!
jr23mx
Posts: 6
Joined: Fri Nov 09, 2018 12:54 am
Location: Monterrey Mexico
Contact:

### best way to check if 2 vectors are parallel

Hello guys, what is the best library or function to check if 2 vectors are parallel?

thanks
mario52
Posts: 2643
Joined: Wed May 16, 2012 2:13 pm

### Re: best way to check if 2 vectors are parallel

Maybe you need a special feature, go into Macros_recipes and Code_snippets, Dialog creation. My macros on Gist.github.
wandererfan
Posts: 2876
Joined: Tue Nov 06, 2012 5:42 pm

### Re: best way to check if 2 vectors are parallel

jr23mx wrote:
Tue Jan 29, 2019 2:47 am
Hello guys, what is the best library or function to check if 2 vectors are parallel?
https://en.wikipedia.org/wiki/Dot_product

Code: Select all

``````x = v1.Dot(v2)/(v1.Length() * v2.Length())
if x = 0 then v1 & v2 are perpendicular.
if x = 1 then v1 & v2 are parallel.
if x = -1 the v1 & v2 are anti-parallel.``````
Watch floating point comparisons.
Posts: 429
Joined: Tue Aug 18, 2015 10:08 am
Location: Germany, Sauerland

### Re: best way to check if 2 vectors are parallel

Testable summary:

Code: Select all

``````tol = 1e-7

# https://en.wikipedia.org/wiki/Dot_product

abs(v4.dot(v5)/(v4.Length * v5.Length)) < tol      # perpendicular
abs(v1.dot(v2)/(v1.Length * v2.Length)-1.0) < tol  # parallel
abs(v1.dot(v3)/(v1.Length * v3.Length)+1.0) < tol  # anti-parallel

abs(v1.dot(v6)/(v1.Length * v6.Length)) < tol      # not perpendicular
abs(v1.dot(v6)/(v1.Length * v6.Length)-1.0) < tol  # not parallel
abs(v1.dot(v6)/(v1.Length * v6.Length)+1.0) < tol  # not anti-parallel

# https://en.wikipedia.org/wiki/Cross_product

v1.cross(v2).Length < tol # parallel
v1.cross(v6).Length < tol # not parallel
v1.cross(v3).Length < tol # parallel
``````
DeepSOIC
Posts: 6840
Joined: Fri Aug 29, 2014 12:45 am
Location: Saint-Petersburg, Russia

### Re: best way to check if 2 vectors are parallel

wandererfan wrote:
Wed Jan 30, 2019 2:34 am

Code: Select all

``````x = v1.Dot(v2)/(v1.Length() * v2.Length())
if x = 0 then v1 & v2 are perpendicular.
if x = 1 then v1 & v2 are parallel.
if x = -1 the v1 & v2 are anti-parallel.``````
That's a very poor quality check, in terms of precision control. Cross-product is better IMO (it's zero for parallel vectors).

Code: Select all

``````v1 = App.Vector(1,      2, 3)
v2 = App.Vector(1+1e-6, 2, 3) #different to v1 by more than standard precision

v1.Length*v2.Length - v1.dot(v2) #returns 4.6e-13, near the accuracy limit of double precision values

v1.cross(v2).Length #returns the actual mismatch between the vectors, times v1.Length*v2.Length

parallel = v1.cross(v2).Length < 1e-7 * v1.Length * v2.Length #reliably returns False for these vectors
``````
OCC also has angular precision, which is 1e-12 radians AFAIR. That level of precision is unreachable with dot product check, but is reachable (barely) with cross product check.