Saturday, December 30, 2017

Practical application of the dot product

I recently had to write an algorithm to decide whether two trains (whose movement directions are known) are moving towards each other or not.

When two trains move towards each other the angle between their direction vectors is larger than 90 degrees. If the track was a straight line the angle would be close to 180 degrees, but tracks are not always straight.

I used the dot (scalar) product as follows:


  1. Calculate the dot product of the train direction vectors. This is equal to cos(angle).
  2. If 90 < angle <= 180 (-1 =< cos(angle) < 0), the two trains are moving towards each other
Note 1: If the track is bending more than 90 degrees, this algorithm will not work:
Note 2: If the trains have passed each other just using the dot product won't work, you also have to check whether the trains are in front of each other (let that be another blog post):

No comments: