dimanche 24 avril 2016

Writing meaningful unit tests for code with floating point inaccuracies (e.g. collision detection)

Let's say I'm writing a physics engine with collision detection, using floats. One method might be to check if two physics objects are intersecting or touching.

class PhysicsObject {

    Vector3f position;

    [...]

    public void isIntersecting(PhysicsObject otherObject) {
        boolean isTouchingOrIntersecting = [do calculations];
        return isTouchingOrIntersecting;
    }

}

For the simulation itself, the floating point precision (even when using floats) is good enough because any inaccuracies will not be visible/noticeable (and immediately corrected in the next simulation step).

But how should I write my unit tests, especially for the boundary cases? I can write tests with two objects far away, and two objects clearly intersecting, but how about them touching exactly? Depending on the float values, the method could return true or false depending on any kind of external condition (compiler, architecture, etc.).

Or should I say that it is not important which result the method returns in this boundary case and so it makes no sense to write a unit test for this case?

When the method's return value is again a float, it's clear that I should use relative errors and epsilons. But I'm using this collision detection problem as an example for the whole class of similar problems when floating points are translated to some "exact" (boolean, integer) result, and how to test those (in the context of 3D graphics / physics code).

Aucun commentaire:

Enregistrer un commentaire