Search code examples
javaperformancedivisionmultiplication

In a simple float operation, is there any difference between multiplication and division?


I was wondering if there could be a a little difference (for performance issues) between multiplication and division in a simple compute like in:

float thing = Mouse.getDY() * 0.1f;
float otherThing = Mouse.getDY() / 10f;

when this kind of things happens a lot, of course, for example in camera position calculation in a 3D game (lwjgl).

Thanks !


Solution

  • Yes, you get different results as 10f can be represented exactly but 0.1f cannot.

    System.out.println(0.1f * 0.1f);
    System.out.println(0.1f / 10f);
    

    prints

    0.010000001
    0.01
    

    Note: using double has far less error, but it doesn't go away without using rounding.

    For a GUI application, you won't see the difference, but it can cause subtle differences in calculations.