Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Convex hull algorithm in 2D sensitive to numeric precision #3455

Open
schillic opened this issue Mar 2, 2024 · 1 comment
Open

Convex hull algorithm in 2D sensitive to numeric precision #3455

schillic opened this issue Mar 2, 2024 · 1 comment
Labels
bug 🐛 Something isn't working discussion 🗣️ Requires human input

Comments

@schillic
Copy link
Member

schillic commented Mar 2, 2024

The following happens because of the -0.0. Nevertheless, the result is unexpected.

julia> v = [[-0.0, 2], [2.0, 0], [1.0, 0], [0.0, 1], [0.0, 1.5]]
5-element Vector{Vector{Float64}}:
 [-0.0, 2.0]
 [2.0, 0.0]
 [1.0, 0.0]
 [0.0, 1.0]
 [0.0, 1.5]

julia> c = convex_hull(v)
4-element Vector{Vector{Float64}}:
 [-0.0, 2.0]
 [0.0, 1.5]
 [1.0, 0.0]
 [2.0, 0.0]

julia> plot([Singleton(x) for x in v], c=:blue, alpha=1)

julia> plot!([Singleton(x) for x in c], c=:red, alpha=1)

julia> plot!(VPolygon(v))

convex_hull

@schillic schillic added the bug 🐛 Something isn't working label Mar 2, 2024
@schillic
Copy link
Member Author

schillic commented Mar 9, 2024

The problem is that sort! gives the wrong order due to the -0.0. It uses the order relation <, which ultimately calls the following Base function:

function cmp(A::AbstractVector, B::AbstractVector)
    for (a, b) in zip(A, B)
        if !isequal(a, b)
            return isless(a, b) ? -1 : 1
        end
    end
    return cmp(length(A), length(B))
end

Here, isequal distinguishes 0.0 and -0.0 and thus sort! outputs [-0.0, 2] before [2.0, 0]. The remaining algorithm checks right turns, which are not precise enough to see the difference, and thus gives the wrong result.

I see two possible solutions:

  1. Sanitize -0.0 values to 0.0.
  2. Change the sort! order relation.

@schillic schillic added the discussion 🗣️ Requires human input label Mar 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug 🐛 Something isn't working discussion 🗣️ Requires human input
Projects
None yet
Development

No branches or pull requests

1 participant