rsencu / pyeuclid

Automatically exported from code.google.com/p/pyeuclid
0 stars 0 forks source link

Intersect Point and LineSegment #8

Open GoogleCodeExporter opened 8 years ago

GoogleCodeExporter commented 8 years ago
I wanted to determine if a point lay on a line segment and it seemed to be
unimplemented, at least in rev31. So I defined a function in class
LineSegment2, returning None if there is no intersection. The square root
operation is expensive so if anyone can do the same thing using only
magnitude_squared, please post it. Here is my code:

def _intersect_point2(self, Q):
    #Given self.p, self.v, Q.x, Q.y
    #Intersects iff (p_Q || v)  & p between end pts.
    if self.p == Q: #projection will be 0
        return self.p
    else:
        diffv = Q - self.p
        d = diffv.magnitude()
        s = self.v.magnitude()
        if (d==0 or s==0):
            return None
        ratio = diffv.dot(self.v) / (d*s) #arccos of this gives theta
        if ratio == 1 and d > 0 and d <= s: #collinear and between 
            return Q
        else:   
            return None

Original issue reported on code.google.com by enrico.m...@gmail.com on 13 Apr 2010 at 2:26

GoogleCodeExporter commented 8 years ago
To test if a point lay on a segment you could simply test if distance is zero, 
no?

If so, the whole function could be reduced to:

def _intersect_point2(self, Q):
    return self.distance(Q) == 0

Or, if instead of True/False you want to return Point/None:

def _intersect_point2(self, Q):
    return Q if self.distance(Q) > 0.0 else None

Both versions are one-liners, so that's probably the reason why it's not 
implemented.

Original comment by rodrigo....@gmail.com on 6 Aug 2014 at 9:24