Ranter
Join devRant
Do all the things like
++ or -- rants, post your own rants, comment on others' rants and build your customized dev avatar
Sign Up
Pipeless API
From the creators of devRant, Pipeless lets you power real-time personalized recommendations and activity feeds using a simple API
Learn More
Comments
-
Beware that JS's round is different than Java round: https://developer.mozilla.org/en-US...
-
Root825576y@571n93r This.
The results would (or should) be identical, though the exact implementation likely differs. -
The more primitive int casting and +0.5 could be convenient for lower level languages
-
devios157706y@571n93r Would it be? How could it possibly be faster than a single add and a truncate? Can it round in a single instruction?
-
571n93r846y@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.
-
devios157706y@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.
-
Root825576y@inaba The standard libraries aren't always the greatest, though! So research research research.
-
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. -
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).
-
@inaba @devios1
Well, there is a 8087 instruction called FRNDINT that does exactly what we need.
https://felixcloutier.com/x86/...
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.
random
toilet thoughts