1

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 !

Damoy
  • 55
  • 1
  • 10
  • 1
    Yes there is a difference. But you'll need to provide more context if you won't want a gazillion people calling you out for premature optimization. – Mysticial Feb 06 '17 at 18:00
  • A bit but I was wondering especially in 3D game calculation, in Java – Damoy Feb 06 '17 at 18:15

2 Answers2

0

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.

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
  • The OP seems to be asking about performance, so I do think you need to say something about that as well. (Note that there are many situations where a bit of extra roundoff is OK if the performance difference is big enough . . . though in that case the OP will obviously need to measure both and decide.) – ruakh Feb 06 '17 at 18:03
  • Oh I see, forgot this, thanks ! So it's not possible that division can be more "performance-reducer" than a multiplication in this kind of examples ? – Damoy Feb 06 '17 at 18:04
  • @Damoy multiplication can be faster, but you need to do *a lot* of them to really matter, i.e. tens of thousands, before it even make a measurable difference, and hundreds of millions, before you will be able to see it. – Peter Lawrey Feb 06 '17 at 19:22
  • @PeterLawrey Ok, thanks for your answers ! – Damoy Feb 07 '17 at 13:06
0

There will be not only performance difference. Mouse.getDY() returns int value, so results will be different too.

In first case you will have float result with fractional part, in second case it will be int converted to float.

I.e. 54 * 0.1f == 5.4f but 54 / 10 == 5

From the performance side float multiplication is faster than division, but I don't think that in the GUI code it can create significant difference.

Uladzimir Palekh
  • 1,846
  • 13
  • 16
  • Since the question asks about `Mouse.getDY() / 10f`, the comment about integer division doesn't (any longer) apply. `54 * 0.1f` likely does not exactly equal `5.4f`, but I haven't checked to be sure. The performance difference between multiplication and division is unlikely to matter. – Lew Bloch Feb 06 '17 at 18:40
  • It was `Mouse.getDY() / 10` in original question. – Uladzimir Palekh Feb 06 '17 at 18:43