distance from given point to given ellipse

后端 未结 7 1945
抹茶落季
抹茶落季 2021-02-05 08:07

I have an ellipse, defined by Center Point, radiusX and radiusY, and I have a Point. I want to find the point on the ellipse that is closest to the given point. In the illustrat

7条回答
  •  被撕碎了的回忆
    2021-02-05 08:22

    There is a relatively simple numerical method with better convergence than Newtons Method. I have a blog post about why it works http://wet-robots.ghost.io/simple-method-for-distance-to-ellipse/

    This implementation works without any trig functions:

    def solve(semi_major, semi_minor, p):  
        px = abs(p[0])
        py = abs(p[1])
    
        tx = 0.707
        ty = 0.707
    
        a = semi_major
        b = semi_minor
    
        for x in range(0, 3):
            x = a * tx
            y = b * ty
    
            ex = (a*a - b*b) * tx**3 / a
            ey = (b*b - a*a) * ty**3 / b
    
            rx = x - ex
            ry = y - ey
    
            qx = px - ex
            qy = py - ey
    
            r = math.hypot(ry, rx)
            q = math.hypot(qy, qx)
    
            tx = min(1, max(0, (qx * r / q + ex) / a))
            ty = min(1, max(0, (qy * r / q + ey) / b))
            t = math.hypot(ty, tx)
            tx /= t 
            ty /= t 
    
        return (math.copysign(a * tx, p[0]), math.copysign(b * ty, p[1]))
    

    Credit to Adrian Stephens for the Trig-Free Optimization.

提交回复
热议问题