dimforge / parry

2D and 3D collision-detection library for Rust.
https://parry.rs
Apache License 2.0
534 stars 93 forks source link

Triangle<f32>::area wildly inaccurate for degenerate triangles (compute in f64 please) #111

Open wlinna opened 1 year ago

wlinna commented 1 year ago

When I compute the area of a triangle with the provided Triangle::area -function, the area can be very wrong.

    let tri = Triangle::new(
        na::Point3::new(1.811, -2.871, 17.464),
        na::Point3::new(1.811, 1.629, 17.464),
        na::Point3::new(1.811, -1.521, 17.464),
    );

    let area = tri.area();

    dbg!(area);

[src/main.rs:37] area = 0.0010679931

Since the triangle is degenerate, the area should be 0. Perhaps ironically, if I calculate with Heron's formula (which tends to give more inaccurate results for needle-like triangles) the resulting area is 0 as it should be. A f64-implementation of Triangle::area also works.

Now I'm not an expert of floating point mathematics nor mathematics in general, but I wonder if Kahan's formula could be replaced with something else? Something called Graham's determinant (f32) also produced 0 when I tried it, but I wonder how its accuracy compares with Kahan's in general. And of course it would be possible to use f64 internally.

This is not the most important issue to solve I think. After all, this is just how Kahan's formula works, and one can use parry-f64 or implement the formula with f64 instead.