Saturday, July 18, 2009

Delphi conversion

So, I'm doing a little Delphi conversion just now and while looking through the code I came over a little bit which didn't quite make sense. Rounding floating point numbers into integers. Now my default has always been to truncate for rounding. Not only is it faster (by far!) but it's easy to predict, and everyone understands it. Now, Delphi's it's nuts!

Dephi seem to have gone out of their way to complicate things, and I can't figure out why. Anyway, after doing a quick search heres the Delphi rules...

The Round function rounds a floating point Number to an Integer value.
The rounding uses Bankers rules, where an exact half value causes a rounding to an even number:

12.4 rounds to 12
12.5 rounds to 12 // Round down to even
12.6 rounds to 13

13.4 rounds to 13
13.5 rounds to 14 // Round up to even
13.6 rounds to 14

Now...why o WHY would you do that.... Round .5 to EVEN! What! Nuts I tellz ya...


KiCHY said...

I used Delphi2-6 for years and also found this confusing behavior. Luckily I could solve my problem with SetRoundMode function (from Math unit maybe...)

Anonymous said...

Totally off topic ;)

I just wondered how do you pronounce your lastname? Rhyming with belly or like "daily"? :)

And get back to work on XEO3 :P

Mike said...

You pronounce it daily - as in The Daily Mail. :)

I'm afriad I'm doing other things at the moment, so I'm not sure when I'll get back to XeO3... *sniff*

Anonymous said...

Hi there, there isnt enough room for me to talk to about this. but ill sum it up as best i can. GTA2 fans of about 5-9 years i believe possibly even longer woud like to speak with u about a project u might really be interested in or if u could just give u sum friendly insight on a email is if intersted as well as Game Hunter. DL GH&GTA2 and come hav a chat wth us please.

Micirio said...

Actually, rounding to even isn't unusual in floating point arithmetic. It's called "exact rounding" or "exactly rounded operations" and defined in the IEEE 754. Using the old school method to round numbers isn't "fair" and could let the value drift away after some operations. So rounding to even generally minimizes the overall error in heavy fp computations.

Anonymous said...

This is called "banker's rounding".
It is useful for business apps. Say, you have some money values, evenly distributed.
If you rounding them down only, values will accumulate slight error and you will end with less number that should be on average