I wrote an algorithm to find the intersection between two line segments some time ago. Coming back to look at it though, I noticed that division by zero is possible in two different places. It's okay if it does this, from a logical perspective I think, but of course the program crashes if it does so. This is the algorithm:
class Segment{
public:
Vector first, second;
bool getIntersection(const Segment arg, Vector * intersect = NULL)const{
Segment segment(b - a, arg.b - arg.a);
double s, t;
// These two equations run the risk of division by zero
s = (-segment.a.y * (a.x - arg.a.x) + segment.a.x * (a.y - arg.a.y))
/ (-segment.b.x * segment.a.y + segment.a.x * segment.b.y);
t = ( segment.b.x * (a.y - arg.a.y) - segment.b.y * (a.x - arg.a.x))
/ (-segment.b.x * segment.a.y + segment.a.x * segment.b.y);
if (s > 0.0 && s < 1.0 && t > 0.0 && t < 1.0)
{
// Collision detected
if (intersect != NULL)
{
intersect->x = a.x + (t * segment.a.x);
intersect->y = a.y + (t * segment.a.y);
}
return true;
}
return false; // No collision
}
};
Division by zero is possible where s
and t
are calculated, if the values behind the divisor are (and may likely turn out to be) all zero. From a geometry perspective, this means the two lines are parallel to each other; parallel lines should never be considered intersecting in this case, even if they overlap perfectly.
Is there a way to allow this function to divide by zero? Assuming of course, that it would not affect the logic behind the algorithm (anything with NANs or INFs will not result in a collision I think)? Or is there a better line segment intersection algorithm I should be using instead?