luageometryradius

How to get circumcircle midpoint and radius in Lua?


I've tried to make a function in Lua to get the circumcircle, circumcenter and radius, but something goes wrong:

local function getCircumcircle (x1, y1, x2, y2, x3, y3)
    local d = 2*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))
    local t1, t2, t3 = x1*x1+y1*y1, x2*x2+y2*y2, x3*x3+y3*y3
    local x = (t1*(y2-y3)+t2*(y3-y1)+t3*(y1-y2))/d
    local y = (t1*(x3-x2)+t2*(x1-x3)+t3*(x2-x1))/d
    local radius = math.sqrt((x1-x)*(x1-x)+(y1-y)*(y1-y))
end

Solution

  • Thanks, Ivo, my bad.

    local function getCircumcircle (x1, y1, x2, y2, x3, y3)
        local d = 2*(x1*(y2-y3)+x2*(y3-y1)+x3*(y1-y2))
        local t1, t2, t3 = x1*x1+y1*y1, x2*x2+y2*y2, x3*x3+y3*y3
        local cx = (t1*(y2-y3)+t2*(y3-y1)+t3*(y1-y2))/d
        local cy = (t1*(x3-x2)+t2*(x1-x3)+t3*(x2-x1))/d
        local radius = math.sqrt((x1-cx)*(x1-cx)+(y1-cy)*(y1-cy))
        return cx,cy,radius
    end
    

    Updated, new version with points:

    -- calculates circumcircle for three points
    local function getCircumcircle(p1, p2, p3)
        local x1, y1 = p1.x, p1.y
        local x2, y2 = p2.x, p2.y
        local x3, y3 = p3.x, p3.y
    
        -- calculate denominator
        local d = 2 * (x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2))
        if math.abs(d) < 0.0001 then  -- points are collinear
            return nil
        end
    
        -- calculate center coordinates
        local t1 = x1*x1 + y1*y1
        local t2 = x2*x2 + y2*y2
        local t3 = x3*x3 + y3*y3
    
        local cx = (t1*(y2-y3) + t2*(y3-y1) + t3*(y1-y2)) / d
        local cy = (t1*(x3-x2) + t2*(x1-x3) + t3*(x2-x1)) / d
    
        -- calculate radius
        local radius = math.sqrt((x1-cx)^2 + (y1-cy)^2)
    
        return {
            x = cx,
            y = cy,
            radius = radius
        }
    end