1

I've seen a few examples of code where they've added 0f to another float which I don't really understand.

The most recent example comes from a advance wars clone made in Monogame and C# if I recall correctly.

                var hit = (int)(basedamage
                                * (Math.Ceiling((double)Life / 10f) / 10f)
                                * ((100f + 0f) / (100f + 0f)));

It seemed to me that it was pointless adding 0 to another number since well.. it's 0. But it's been clearly defined as a float so I assume there's a reason to that.

I asked a question on a game dev discord I was on and one of them told it that it was 'maybe to add precision' but he didn't seem so sure himself. I can't find any information on google (and to be truthful, I don't really know how to phrase what I'm trying to find out properly)

So, is it just to add more 'precision' to a float or is there another reason as to why some people do this?

Ducktor
  • 337
  • 1
  • 9
  • 27
  • possible answer: https://stackoverflow.com/questions/48255293/in-ieee-754-why-does-adding-negative-zero-result-in-a-no-op-but-adding-positive – DaBler May 31 '18 at 18:06
  • 6
    Per the IEEE 754 standard, adding +0 is not an identity operation because it changes −0 to +0. However, it is rare that applications need that, and it is not a factor in the operation you show, `100f + 0f`. Not every person who writes code has sensible reasons for what they write. If there are not accompanying comments or other documentation explaining the author’s purpose, then ignore it. One origin for code like this is that some part of it was automatically generated by other software or substitution, and trivial operations in it have not been reduced. – Eric Postpischil May 31 '18 at 18:27
  • I see there is also x/x here (where x = 100f + 0f) which I suppose must be 1f for nonzero finite numbers such as 100f. Hmm. If there is a history of the source code (e.g. Git) you can see who wrote that code, and see if they said anything about, or ask them. E.g. git blame tells who committed each line of the code. – Robert Dodier May 31 '18 at 19:50
  • Given other oddities of this code I support Eric's idea of the code being auto-generated by some (not very clever) tool. – SergGr May 31 '18 at 20:35

1 Answers1

3

There is no reason to do this. x * ((100f + 0f) / (100f + 0f))) == x for all ordered x. This code may have arisen from autogeneration, from overly narrow code edits over time, or as a result of someone's mistaken beliefs about floating point computation. But in any case, it is not necessary.

Sneftel
  • 40,271
  • 12
  • 71
  • 104