Comment On Correcter Rounding

Rounding is one of those things that seems to be a fairly difficult for programmers. Although the built-in rounding functions of many programming languages have helped a lot of programmers embarrass themselves, some still choose (or, in C/C++, are forced) to take a stab at it. But it's just a simple combination of floor(). ceil(), and arithmetic, you might think. An anonymous submitter ("Isostar") found out that some choose to use sprintf() for this ... [expand full text]
« PrevPage 1 | Page 2Next »

Re: Correcter Rounding

2006-01-09 15:16 • by A Wizard A True Star

I bet RoundCorrect3, when it's eventually written, will use this obscure function known as abs() to allow for the possibility of negative numbers. Innovation!


 


 

Re: Correcter Rounding

2006-01-09 15:17 • by php user
So, what's wrong with just using round()?

Re: Correcter Rounding

2006-01-09 15:22 • by mlathe
56092 in reply to 56091

Anonymous:
So, what's wrong with just using round()?


maybe it doesn't exist?

Re: Correcter Rounding

2006-01-09 15:24 • by koning_robot
56093 in reply to 56091
Anonymous:
So, what's wrong with just using round()?




PHP also features better_round(), which is a better round().

Re: Correcter Rounding

2006-01-09 15:26 • by ferrengi
OK,

So he wrote one function which I cannot follow the logic of and figure
out what it does but suffice to say that it can't possibly be a good
solution. Then he came up with something which seems to round down to
the nearest whole number if the decimal portion is < .01

If the decimal portion is greater than .01, the number gets rounded up to the nearest whole number.

A great way to "round off"!



Now, to correct this problem, he decides to use .5 as the cutoff. Much
better than the first two attempts. This actually seems to work
correctly for numbers with only one decimal place. So, what function
needs to be called if the number needs to be rounded off to the nearest
few decimal places instead of the nearest whole number? Is there a
function RoundCorrect3() that deals with rounding to one decimal place
and RoundCorrect4() to deal with rounding to 2 places? etc...



And what happened to the globalRounding variable. Why was it taken out of the second and third rendition of this function?



That's what I was able to come up with.

Re: Correcter Rounding

2006-01-09 15:27 • by mlq
56095 in reply to 56091
If everybody just went off and used round(), then we'd have nobody to mock.  Personally, I am thankful for those who exist only to serve as warnings to others.

Many kinds of rounding

2006-01-09 15:28 • by AlpineR
I'd just like to point out that there are
many kinds of rounding. I'm afraid to guess which one this code is attempting to implement.

Re: Correcter Rounding

2006-01-09 15:29 • by R K Quinlivan
Was this written by someone with a college degree?! Good lord, I am going to have to work with these people some day. :-(

Re: Correcter Rounding

2006-01-09 15:30 • by Great Griff
56099 in reply to 56091

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:


Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189


 


 

Re: Correcter Rounding

2006-01-09 15:30 • by boohiss
56100 in reply to 56095
I wish ASP VBScript had floor and ceiling functions. I have to write a 5 line 'if' statement everytime I want the ceiling of something.

Re: Correcter Rounding

2006-01-09 15:30 • by mlathe
Alex Papadimoulis:

float Round(float val)
{
  TCHAR tmpStr[128];
  int intVal, decVal;
  int i;

  if(globalRounding)
  {
    _stprintf(tmpStr, _T("%0.1f"), val);
    intVal = _ttoi(tmpStr);

    for(i = 0; i < (int)_tcslen(tmpStr); i ++)
    {
      if(tmpStr[i] < '0' || tmpStr[i] > '9')
      {
        decVal = _ttoi(&(tmpStr[i + 1]));
      }
    }
    if(decVal <= 3)
    {
      val = (float)intVal;
    }
  }
  return val;
}




Correct me if i'm wrong. But the Round function seems to isolate the decimal point and get the next char. If that is <=3 then round down, else just return the origional number.


thus:
1.2 ==> 1.0
1.3 ==> 1.0
1.4 ==> 1.4
1.9 ==> 1.9

not a very good rounding function!


also why does Round return a float?

Re: Correcter Rounding

2006-01-09 15:32 • by Disgruntled DBA
They all said it was daft to write a rounding function in C.  So, just to show 'em, I built it anyway.  The first rounding function sank into the swamp.  So I built a second rounding function, and that sank into the swamp.  I built a third rounding function, and that burned down, fell over, and then sank into the swamp, but the fourth one stood up, and that's what you're getting, lad.  The strongest rounding function in these isles.....

Re: Correcter Rounding

2006-01-09 15:35 • by TankerJoe
Alex Papadimoulis:


  if(globalRounding)







The real WTF here is that he keeps a global flag to tell if he should acctually do any rounding.



In addition... he forgot to write that into his follow up functions.  WTF

Re: Correcter Rounding

2006-01-09 16:02 • by lucky luke
Alex Papadimoulis:


int RoundCorrect(float number)

{
if(number-(int)number<0.01)
return (int)number;
else
return (int)(number+1);
}



maybe... just maybe in RoundCorrect() he thought that number - (int)number would somehow cast the returned value to be an int too and be magically rounded already thus if the number was close to 0 it would be rounded down and the other possible value would have been 1. So instead of writing == 0 he wrote < 0.01
I mean really who hasn't defined 0 as being < 0.01

A Wizard A True Star

: abs()  you mean they finally installed an antilock braking system for programs so they won't freeze up? ~ or is that a windows only thing
;)

Re: Correcter Rounding

2006-01-09 16:06 • by JAlexoid
56109 in reply to 56094
I would have to confess that I too did theese function, but they did serve a purpose the accomodates the rounding practices of the company's accountants. And I have to have exact VAT sum calculated and it may be WAY OFF when VAT is 18%.

Re: Correcter Rounding

2006-01-09 16:07 • by grmcdorman
Take a closer look at the first "rounding" function - specifically, what it will do for numbers like 1.01 and 1.007:
  1.01 -> 1
  1.007 -> 1.007
(ttoi will ignore leading zeros, so 01, 0001, and 00001 are all the same value: 1)

Re: Correcter Rounding

2006-01-09 16:12 • by Strydyr

Assuming there's no Round function:


(int) (number + 0.5)


should get the job done.


In fact 0.5 could instead be a global variable, so that "correctness" can be tweaked on the fly!


 

Re: Correcter Rounding

2006-01-09 16:21 • by a goat
56112 in reply to 56099
Anonymous:

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:


Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189


 


 



 


I don't see Bankers' Rounding in that list.  I've had to do the rounding function in C# because the C# Math.Round() function performs Bankers' Rounding and the spec said to use Round Half Up rounding (ironically enough, this was at a Bank)


 


Bankers' Rounding is essentially Round Half Towards Nearest Even


3.4 goes to 3


3.5 goes to 4


3.6 goes to 4


 


4.4 goes to 4


4.5 goes to 4


4.6 goes to 5

Re: Correcter Rounding

2006-01-09 16:23 • by a goat
56113 in reply to 56099
Anonymous:

There's lots of reasons to never use a language's built in rounding function. Mainly it will never do what your users want. People (and the government, especially the IRS) are passionate about rounding and there are many, many ways of doing it:


Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189


 


 



oops, just found it

Re: Correcter Rounding

2006-01-09 16:27 • by GoatCheez
56114 in reply to 56111
Strydyr:

Assuming there's no Round function:


(int) (number + 0.5)


should get the job done.


In fact 0.5 could instead be a global variable, so that "correctness" can be tweaked on the fly!


 



If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));

Re: Correcter Rounding

2006-01-09 16:44 • by MePogo
56116 in reply to 56097
Anonymous:
Was this written by someone with a college
degree?! Good lord, I am going to have to work with these people some
day. :-(


One of these days, I'm going to _be_ one of these people...

Re: Correcter Rounding

2006-01-09 16:51 • by CornedBee
56118 in reply to 56114
GoatCheez:

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));


That's one superfluous cast:

return (int)((number > 0) ? (number + .5) : (number - .5));

Re: Correcter Rounding

2006-01-09 16:53 • by Alun Jones
56120 in reply to 56114

GoatCheez:

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));


I once worked on a program that had, for ten years, been used by companies controlling multi-million dollar projects to the accuracy of one penny.  Reading from a dBase file, and converting all decimals to pseudo-"fixed point" integers, the code included sections like this:


  FIXEDPOINT = INTEGRAL_PART * 10 ** MANTISSA + FRACTIONAL_PART


(Yes, that's FROTRAN)


That's great for positive numbers - "10.03" goes to 10 * 10^2 + 3 = 1003.


But for negative numbers, "-10.03" goes to -10*10^2+3 = -9997.


Even after demonstrating this to the original developer of the code (and president of the company), he refused to acknowledge that it existed, and I had to fix it in stealth-mode.


In another project, I wrote two functions for evaluating the "British Standard for Roundness", but I don't think this is the kind of round they were talking about.

Re: Correcter Rounding

2006-01-09 17:06 • by hermit
I HATE YOU

Re: Correcter Rounding

2006-01-09 17:29 • by ferrengi
56124 in reply to 56122
Anonymous:
I HATE YOU




Who?

Re: Correcter Rounding

2006-01-09 17:43 • by sao
56126 in reply to 56103
Disgruntled DBA:
They all said it was daft to write a
rounding function in C.  So, just to show 'em, I built it anyway.  The
first rounding function sank into the swamp.  So I built a second
rounding function, and that sank into the swamp.  I built a third
rounding function, and that burned down, fell over, and then sank into
the swamp, but the fourth one stood up, and that's what you're getting,
lad.  The strongest rounding function in these isles.....

FIRST!!.... post to make me laugh  ;-)

good job! =)

Re: Correcter Rounding

2006-01-09 17:50 • by GoatCheez
56127 in reply to 56118
CornedBee:
GoatCheez:

If there is an abs(), then it should use it too... negative values often get overlooked in rounding functions... I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));


That's one superfluous cast:

return (int)((number > 0) ? (number + .5) : (number - .5));


Of course, why not just go further with:
return (int) (number + ((number > 0)?0.5:-0.5));

Re: Correcter Rounding

2006-01-09 18:00 • by Otto

When writing financial applications, I prefer to use trunc(). Then I take whatever is truncated and add it to my own account.


I got the idea from Superman 3.


 


 


 

Re: Correcter Rounding

2006-01-09 18:19 • by DrDoom
56131 in reply to 56091

Some programmers are reluctant to use in-build rounding functions for historical reasons. Those being that some CPUs and/or OSs chose different ways to round. That is some rounded up while some rounded down. As a result you could get 0.5 coming up as 0 on some test systems and 1 on others.


Of course there are always those that don’t know what they are doing or need to justify 100 hours overtime for solving a complicated problem but do not have any code to show for it.


 


Sad but true.


 

Re: Correcter Rounding

2006-01-09 18:36 • by et tu?
56132 in reply to 56131
Sometimes I just like to imagine what I would do if I were the manager and decided to do a code review and found something like this (instead of having to clean it up, like I do now).  The first instinct, of course, is to call security and have the offending "developer" escorted out of the building, into the back alley, and beaten within an inch of his life.  That might make me feel better, but would he have really learned his lesson?

Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.

Re: Correcter Rounding

2006-01-09 18:39 • by DerGuteMoritz
56133 in reply to 56103
But all I want to do is striiiiiiiiiiiiing manipulation!

Re: Correcter Rounding

2006-01-09 18:54 • by Gene Wirchenko
56134 in reply to 56132
Anonymous:
Sometimes I just like to imagine what I would do if I were the manager and decided to do a code review and found something like this (instead of having to clean it up, like I do now).  The first instinct, of course, is to call security and have the offending "developer" escorted out of the building, into the back alley, and beaten within an inch of his life.  That might make me feel better, but would he have really learned his lesson?


Could he ever?

Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.


That will not work.  With an employee, you can not refuse to pay them for their time.

You definitely have an extreme approach.  I wish it were not so justified.

Sincerely,

Gene Wirchenko

Re: Correcter Rounding

2006-01-09 19:13 • by php user
56136 in reply to 56093
Anonymous:
PHP also features better_round(), which is a better round().


Umm, no it doesn't.

Re: Correcter Rounding

2006-01-09 19:58 • by Stoffel
56138 in reply to 56099
Anonymous:

There's lots of reasons to never use a
language's built in rounding function. Mainly it will never do what
your users want. People (and the government, especially the IRS) are
passionate about rounding and there are many, many ways of doing it:


Look at all the different ways to round: http://www.pldesignline.com/howto/showArticle.jhtml;?articleID=175801189


 


 



Excellent point.  Video and audio coding specs usually have some sort of convention like:

/ - divide w/ truncation

// - divide w/ round toward -inf

/// - divide w/ round toward 0



etc.  I saw it get up to 4 slashes once.  So A / B != A //// B for all values of A & B.

Re: Correcter Rounding

2006-01-09 20:03 • by Stoffel
56139 in reply to 56138
er, make that for some values.

Re: Correcter Rounding

2006-01-09 20:04 • by BtM
56140 in reply to 56114
GoatCheez:
Strydyr:

Assuming there's no Round function:


(int) (number + 0.5)


should get the job done.


In fact 0.5 could instead be a global variable, so that "correctness" can be tweaked on the fly!


 



If there is an abs(), then it should use
it too... negative values often get overlooked in rounding functions...
I usually do something like:

return (number > 0)?((int)(number+ 0.5)):((int)(number-0.5));




What if you're rounding a value that's greater than INT_MAX?



It's the corner cases that you have to watch out for...

Re: Correcter Rounding

2006-01-09 20:24 • by sao
56145 in reply to 56140
tmpint = ((number > 0)?((int)(number+ 0.5)):((int)(number-0.5)));
tmpint > maxint ? throw Exception("Arrrrrrgggggggg.....");
return tmpint;


and i dont care if the syntax is wrong.

Re: Correcter Rounding

2006-01-09 20:56 • by BiggBru

I'm sure he'll have things figured out by the time RoundCorrect5() comes along...


By the way, are the C/C++ built-in rounding functions terrible enough to justify... this?

Re: Correcter Rounding

2006-01-09 21:01 • by no name
56151 in reply to 56145

tmpint = ((number > 0)?((int)(number+ 0.5)):((int)(number-0.5)));

tmpint > maxint ? throw Exception("Arrrrrrgggggggg.....");

return tmpint;





WTF???

Re: Correcter Rounding

2006-01-09 21:42 • by zephc
Sometimes bad code is just *tiring* to look at. Not that it is difficult, but trying to figure out "Why The F***?!?", if just becomes exhausting. This is one of them.

Re: Correcter Rounding

2006-01-09 23:57 • by dent
56157 in reply to 56100
Anonymous:
I wish ASP VBScript had floor and ceiling functions. I have to write a 5 line 'if' statement everytime I want the ceiling of something.


It does have the ability to create your own functions though, doesn't it?  ;)

Re: Correcter Rounding

2006-01-10 00:03 • by josh
56158 in reply to 56127
GoatCheez:
Of course, why not just go further with:
return (int) (number + ((number > 0)?0.5:-0.5));


pff.

return (int)(number + (number > 0) - 0.5);

Re: Correcter Rounding

2006-01-10 02:54 • by isostar
56160 in reply to 56150
There are no built in rounding functions in C.

Re: Correcter Rounding

2006-01-10 03:05 • by Rolf
56161 in reply to 56151
Anonymous:

tmpint = ((number > 0)?((int)(number+ 0.5)):((int)(number-0.5)));

tmpint > maxint ? throw Exception("Arrrrrrgggggggg.....");

return tmpint;





WTF???


"The castle of .. aarrrgg....."

Re: Correcter Rounding

2006-01-10 03:41 • by gannimo
56162 in reply to 56145
I don't think, you can test if an int value is bigger than the biggest possible int value ;)

Re: Correcter Rounding

2006-01-10 04:21 • by dhromed
56163 in reply to 56162
Anonymous:
I don't think, you can test if an int value is bigger than the biggest possible int value ;)


One might as well use the literal False.

Re: Correcter Rounding

2006-01-10 04:25 • by guest
56164 in reply to 56158

pff.

return (int)(number + (number > 0) - 0.5);


Don't do this in VB. True is not what you think it is :)

Re: Correcter Rounding

2006-01-10 05:02 • by teedyay
56166 in reply to 56132
Anonymous:
Let's take another approach.  Give the developer a laptop, throw him in a room with no Internet connection, and order him not to leave until he has a 100% fully functional, well tested (with test result output available) rounding function or failing that, a resignation letter explaining that he really doesn't know how to code and we will never see or hear from him again.  We will then frame his resignation letter and show it to all new hires when we make them a job offer, with the added clause that if they regularly produce code of this quality, they will owe the company every single dollar that we have ever paid them, with interest.

^ This.


Anonymous:
I've had to do the rounding function in C# because the C# Math.Round()
function performs Bankers' Rounding and the spec said to use Round Half
Up rounding (ironically enough, this was at a Bank)

Yeah, me too. After a nightmare project or two, we've taken to explaining to the client up front about the different types of rounding, telling them that Bankers' rounding is (apparently) the standard, and asking them which type they'd like us to use. So far we've not met anyone (even in accounts departments) who has even heard of Bankers' rounding, and they've always gone for if-it's-a-half-round-up.

We also try to pre-empt their whinges about rounding errors (mostly occurring from our painful 17.5% VAT system), and manage to bring them down from their initial position of "we want everything to add up exactly to the penny in every circumstance, and we don't want to see any fractions of pence" before we write a single line of code.

Re: Correcter Rounding

2006-01-10 05:50 • by Dagur
There's nothing wrong with using sprintf. In fact that's the recommended way in the perl cookbook.

I don't get what that guy is doing in that function though.

Re: Correcter Rounding

2006-01-10 05:59 • by johnl
56172 in reply to 56166
Let's take another approach.  Give the
developer a laptop, throw him in a room with no Internet connection,
and order him not to leave until he has a 100% fully functional, well
tested (with test result output available) rounding function or failing
that, a resignation letter explaining that he really doesn't know how
to code and we will never see or hear from him again.  We will then
frame his resignation letter and show it to all new hires when we make
them a job offer, with the added clause that if they regularly produce
code of this quality, they will owe the company every single dollar
that we have ever paid them, with interest.

So in order to get him to develop a working function, you want to remove the ability to do this: http://www.google.co.uk/search?q=c%23+rounding , right?  Maybe you should hand in your letter of resignation along with him.

And before coming to this site, I'd never heard of Bankers' rounding.  I had to look it up again to know what we were talking about.
« PrevPage 1 | Page 2Next »

Add Comment