Hello guys, what is the best library or function to check if 2 vectors are parallel?
thanks
best way to check if 2 vectors are parallel
Forum rules
Be nice to others! Respect the FreeCAD code of conduct!
Be nice to others! Respect the FreeCAD code of conduct!
Re: best way to check if 2 vectors are parallel
Maybe you need a special feature, go into Macros_recipes and Code_snippets, Topological_data_scripting.
My macros on Gist.github here complete macros Wiki and forum.
My macros on Gist.github here complete macros Wiki and forum.
- wandererfan
- Veteran
- Posts: 6309
- Joined: Tue Nov 06, 2012 5:42 pm
- Contact:
Re: best way 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.
Re: best way to check if 2 vectors are parallel
Testable summary:
Code: Select all
tol = 1e-7
v1 = FreeCAD.Vector(1.0, 1.0, 0.0)
v2 = FreeCAD.Vector(2.0, 2.0, 0.0)
v3 = FreeCAD.Vector(-1.0, -1.0, 0.0)
v4 = FreeCAD.Vector(0.0, 2.0, 0.0)
v5 = FreeCAD.Vector(2.0, 0.0, 0.0)
v6 = FreeCAD.Vector(1.0, 0.5, 0.0)
# 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
- Veteran
- Posts: 7896
- Joined: Fri Aug 29, 2014 12:45 am
- Location: used to be Saint-Petersburg, Russia
Re: best way to check if 2 vectors are parallel
That's a very poor quality check, in terms of precision control. Cross-product is better IMO (it's zero for parallel vectors).wandererfan wrote: ↑Wed Jan 30, 2019 2:34 amCode: 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.
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