38
ruhe
6y

While sitting on the toilet, it struck me:

int y = (int) (x+0.5); //x is a float

is exactly the same as:

int y = Math.round(x);

It's such a simple thought, yet, I realized that just now.

Comments
  • 13
    Would yield the same results but isn't exactly the same...
  • 2
    Beware that JS's round is different than Java round: https://developer.mozilla.org/en-US...
  • 3
    @571n93r This.
    The results would (or should) be identical, though the exact implementation likely differs.
  • 2
    @Root Yup. Round will be optimised compared to adding then casting
  • 2
    The more primitive int casting and +0.5 could be convenient for lower level languages
  • 0
    @571n93r Would it be? How could it possibly be faster than a single add and a truncate? Can it round in a single instruction?
  • 3
    @devios1 casting from a floating point value to integer isn't just truncating though. They are stored in different ways. If you look at how floating point numbers are stored im binary (we did this at university and I still cant wrap my head around it) its very different to how an integer is stored.
  • 1
    @devios1 twos compliment is for integers and dealing with negative numbers :)
  • 1
    @571n93r You’re right floating points are stored differently. I don’t remember exactly how they are converted either but I thought it could be done in one instruction. I could be wrong.
  • 3
    @trollonaboat remember kids: don’t try to outsmart your compiler
  • 1
    @inaba The standard libraries aren't always the greatest, though! So research research research.
  • 4
    Well, I see the problem that floating point numbers need to be handled with a bit of caution.

    Example, we have a complex formula that gives us (on paper) a result of '1.5'.
    Because of the way floats are stored, it may be represented internally by something like '1.499999...' or '1.5000...1'

    Now add 0.5f there: using the cast-round, one time you get 1, another time you get 2. With round you get the correct result because it knows how to deal with it.
  • 1
    Especially at value 0.5. In some languages there's a setting to round up or to round down (rounding down being an American accountancy thing).
  • 2
    @Root Better be sure and use assembly for everything!
  • 4
    @inaba @devios1
    Well, there is a 8087 instruction called FRNDINT that does exactly what we need.

    https://felixcloutier.com/x86/...
  • 2
    Not true for negative integers
  • 1
    Way to increase your codes "wtfs per minute"
Add Comment