Rounding Algorithms
dtmos writes "Clive Maxfield has an interesting article up on PL DesignLine cataloging most (all?) of the known rounding algorithms used in computer math. As he states, "...the mind soon boggles at the variety and intricacies of the rounding algorithms that may be used for different applications ... round-up, round-down, round-toward-nearest, arithmetic rounding, round-half-up, round-half-down, round-half-even, round-half-odd, round-toward-zero, round-away-from-zero, round-ceiling, round-floor, truncation (chopping), round-alternate, and round-random (stochastic rounding), to name but a few." It's a good read, especially if you *think* you know what your programs are doing."
1.44th post!
Round down and put the extra aside. Say, in your own account. Like the have-a-penny-need-a-penny jar at the local Gulp-n-Blow.
especially if you *think* you know what your programs are doing.
Pfft... I've been writing programs and working with computers for over 25 years. I *STILL* haven't figured out what they are doing. Come to think of it, I could say the samething about my wife.
If "disco" means "I learn" in Latin, does "discothèque" mean "I learn technology"?
my favorite rounding algorithm is pi(r)^2.
The theory of relativity doesn't work right in Arkansas.
- Mountain Dew
- Couch
- Lack of willpower
- Utter disdain for annual resolutions I made less than a week ago
- DiGiorno's pizzas.
Seems to work.I think you mean:
Round-up, Round-down, get around-toward-nearest,
I get around-half-up,
Yeah,
Get around-half-down, round-half-even, round-half-odd, I get around-toward-zerowooooooHHHHooo!
blarg.
I don't think I know what my programs are doing all the time... :)
I just hope they play nice when I'm not watching.
...where it discusses the various rounding methods. I had actually thought of/used most of them. The one that was new to me was the round-half-even (banker's rounding). Very cool idea, and I had no idea it was commonly used.
This is a great reference article! If you are programmer working with numerical algorithms, keep this article handy.
Helping with organizational effectiveness is our job.
Rounding to the nearest square?
When I need to implement rounding, I add .5 and then truncate. I believe (perhaps naively) that this is efficient because of the lack of branching.
Computer games should round randomly.
This means that every little bonus that the player gets might have an impact on the integer result. Example: phaos.
The "other" neat thing is that the expected value of
floor(x+rand()) == x
with 0.0=0.0
I'm still trying to figure out what people mean by 'social skills' here.
[Fuck Beta]
o0t!
Far from being merely academic, this could be useful for all the banking accounting programmers out there collecting fractional amounts of money. A third of a cent here, a tenth of a cent there, pretty soon it adds up to real money!
try { do() || do_not(); } catch (JediException err) { yoda(err); }
I mostly program using fixed integer arithmetic, so I don't do much plain rounding. But I do frequently need to do division with rounding up to nearest integer value. For that I use:
Wanted: witty unique signature. Must be willing to relocate.
Why not just round to the nearest in all cases?
If you're worried about cumulative rounding error buildup, then don't round until after you've accumulated. After all, you're not adding things up with pencil and paper anymore, are you?
If you disagree with me on social issues, then it's pretty clear that you are a narrow-minded bigot.
I'm currently working with floating point accumulation and I've come to realize that rounding is unbelievably important when it comes to floating point. For long accumulations or a series of operations you need round to nearest functionality, but even this can be insufficient depending on the nature of the numbers your adding. If truncation is used however, although the easiest to implement in hardware, the error can add up so fast that it'll stun you. It's good to see a fairly comprehensive summary of techniques out there that doesn't require wading through the literature.
Rounding towards the nearest neighbour is the default and ubiquitously used rounding mode. The complementary rounding modes (round toward -+ infinity or 0) are useful for doing calculations with interval arithmetic: a calculation can be performed twice with opposing rounding modes to derive an interval value for the result. If all operations are performed in this way, the final result of a complex calculation is expressed as an interval providing the range in which the real value will be (remember, often floating point numbers only approximate the real number). Using such a package can save you the trouble of performing error analysis. An article in the Journal of the ACM provides the details for implementing this feature.
Almost correct, but I think it can be simplified to the following:
quidquid latine dictum sit altum videtur.
And the IEEE standard for rounding is Banker's Rounding, or Even Rounding, plus whatever other names it goes by. When rounding to the nearest whole number, when the value is exactly halfway between, i.e. 2.5, the rounding algorithm chooses the nearest even number. This allows the distribution of rounding to happen in a more even distributed manner. Always rounding up, which is what US kids are taught in school, will eventually create a bias and throw the aggregates off.
2.5 = 2
3.5 = 4
So, 7% GST on a $1 purchase, yields $1.07. On a $1.01 purchase, yields $1.09 ($1.01 + $0.0707 rounded to $0.08 = $1.09).
It used to be that Quebec added their 8% PST not on the amount excluding GST, but the amount including GST, rounded up of course, and it too was rounded. So $1.01 + 7% GST = $1.09. $1.09 + 8% PST = $1.18. Dunno if they replaced that with the 15% "harmonized" sales tax (paid to the Feds and then partially reimbursed to the province to be equivalent to the combination of 7% GST and average provincial 8% PST -- apparently Quebec was the only province to calculate their PST on top of the GST), but I doubt it.
You could've hired me.
So it turns out instead of 2, there are more like 9 different types of people.
The classics:
Those who round a glass of water up (Has been filled)
Those who round it down (Has been emptied)
The oddballs:
The round-half-up crowd(Half or greater is filled)
The round-half-down crowd(Half or less is empty)
The round toward zero types(Always empty)
The round away from zero groupies(Always Full)
The round alternate weirdos(They get interesting when you give them two glasses)
The round random subset(Carry around a coin or die to decide such problems)
And finally...
The truncate ones who cannot handle such a problem and smash the glass to make sure it is empty.
If this signature is witty enough, maybe somebody will like me.
... nothing in comparison to trying to figure out what the compiler is doing. My beautiful code goes into one end and comes out as an executable file that segfaults. Of course, some twit always say the problem is with my beautiful code and not the stupid compiler.
Really? I thought it was more like:
I know your comment is both off topic and just plain silly but the correct conversion between deg F and deg C is F=(C*1.8)+32
What's the difference between round-toward-zero and truncate is? Or floor round and round down? Or ceiling round and round up?
Play Command HQ online
between round to zero and floor, and round to infinity and ceiling?
autopr0n is like, down and stuff.
Discovered the hard way that Fix() in VB doesn't act as I would expect.
Fix((580# * 1.3636)*10000#) gives 7908879 rather than 7908880
This way to the egress...
...for all things floating-point: What Every Computer Sceintist Should Know About Floating-Point Arithmetic. I keep a copy of this handy whenever I have to play with floats and doubles (except for the odd game of Water Tennis, of course).
Just junk food for thought...
These days kids are not taught to round. Instead you just do the compuations at absurdly large precision then on the last step round off. This way you don't accumulate systematic round-off error. It's good as long as you have the luxury of doing that. It used to be that C-programmers had a cavalier attitude of always writing the double-precision libraries first. Which is why Scientific programmers were initially slow to migrate from fortran.
These days it's not so true any more. First there's lots of good scientific C programmers now so the problem of parcimonius computation is well appreciated. Moreover the creation of math co-processing, vector calcualtions, and math co-processors often makes it counter-intuitive what to do.
For example it's quite likely that brute forcing a stiff calculation is double precision using a numeric co-processor will beat doing it in single precision with a few extra steps added to keep the precision in range. So being clever is not always helpful. people used to create math libraries that even cheated on using the full precision of the avialable floating point word size (sub-single precision accuracy) since it was fast (e.g. the radius libs for macintoshes) Pipelining adds more confusion, since the processor can be doing other stuff during those wait states for the higher precision. Vector code reverse this: if you are clever maybe shaving precision willlet you double the number of simultanoeus calcualtions.
In any case, what was once intuitive: minimal precision and clever rounding to avoid systematic errors means faster computation is no longer true.
Of course in the old days people learned to round early in life: no one wanted to use a 5 digit precision slide rule if you could use a 2 digit precision slide rule.
Some drink at the fountain of knowledge. Others just gargle.
...in federal pound-me-in-the-ass prison.
your algorithm always rounts 0.5 up.
Some drink at the fountain of knowledge. Others just gargle.
-5.8 --> -5.8+0.5 --> -5.3 --> truncate(-5.3) = -5.0
which is not what you want.
In c++, using std::floor will give the correct results with this method though
-5.8 --> -5.8+0.5 --> -5.3 --> floor(-5.3) = -6.0 (correct)
whereas :
-5.3 --> -5.3+0.5 --> -4.8 --> floor(-4.8) = -5.0 (correct)
*buys TedTschopp 42 metric beers* It's a bloody shame no one recognized the reference.
best web host ever
It sounds like you are saying, instead of rounding to the nearest unit, round to the nearest half unit. If you had read the article you would know that there is no theoretical difference what place value you decide to round to.
You think you can just eliminate the 1/2 bias like that? Ok, now you know what to do with the number 3.5. Now what do you round 3.75 and 3.25 to? You are just shifting the rounding down one binary digit.
You say to not round until the end? You miss the point of rounding, which is necessary due to efficiency, memory, or hardware concerns. Nobody makes 10000 bit ADCs, and even if they did, you'd still need to round the 10001st bit.
I was expecting something a little better than this, like maybe some fast code to study and use.
In Soviet America the banks rob you!
Bzz, compiler error, assignement without left-hand argument. Wow thats a horrible piece of code. If you were going to call a set_sales() function, you would have to pass 0 as an arguement. Otherwise you would need a function to return a reference so that you could you could assign it like that.
Pete/Petri "damn, my chainsaw is clogged with 1's and 0's again." --clyde
Nope, we're still one of the 2-3 places in the world to tax our taxes.
Try Corewar @ www.koth.org - rec.games.corewar
is the one used by richard pryor's character in superman iii to steal all of the half pennies from his company's payroll and become fabulously rich
Nah, I think these guys did it better...
// TODO: Insert Cool Sig
Try this. It just might be a lot faster. It copies the sign bit from the value to be rounded to the 0.5, adds 0.5 to positive values or subtracts 0.5 from negative values, then truncates. Of course, I haven't tried it so it just might be slower than a properly inlined and optimized floor() function. But it should be faster if your architecture can move values directly between general and fp regs (unlike SPARC... :-P):
// IEEE sign bit is first // set sign bit for half // add .5 to positive x, subtract .5 from negative x // truncate and return
typedef union masker
{
double d;
int64_t n;
} masker_t;
int round( double x )
{
static const int64_t mask = 1LL 63;
masker_t half;
half.d = 0.5;
masker_t a;
a.d = x;
half.n |= ( a.n & mask );
x += half.d;
return( ( int ) x );
}
Why would you even bother rounding if you didn't know whether the result was going up or down?
No sig for you!
I would say that $3.00 is just as precise as $3.21. If you want less precision, you have to go to $3...
Repton.
They say that only an experienced wizard can do the tengu shuffle.
learned from Ratt:
Out on the streets, that's where we'll meet
You make the night, I always cross the line
Tightened our belts, abuse ourselves
Get in our way, we'll put you on your shelf
Another day, some other way
We're gonna go, but then we'll see you again
I've had enough, we've had enough
Cold in vain, she said
(Pre-chorus)
I knew right from the beginning
That you would end up winnin'
I knew right from the start
You'd put an arrow through my heart
(Chorus)
Round and round
With love we'll find a way just give it time
Round and round
What comes around goes around
I'll tell you why
Dig
Lookin' at you, lookin' at me
The way you move, you know it's easy to see
The neon light's on me tonight
I've got a way, we're gonna prove it tonight
Like Romeo to Juliet
Time and time, I'm gonna make you mine
I've had enough, we've had enough
It's all the same, she said
(Pre-chorus)
(Chorus)
Yeah!
Solo
Out on the streets, that's where we'll meet
You make the night, I always cross the line
Tightened our belts, abuse ourselves
Get in our way, we'll put you on your shelf
(Chorus)
Round and round
With love we'll find a way just give it time, time, time, time
Round and round
What comes around goes around
I'll tell you why, why, why, why
Round and round
// TODO: Insert Cool Sig
</silly>
Actually, that seems like an interesting concept. I always felt that my computer science class needed to be more challenging, and now I know how to do it!
Why is it that when you believe something it's an opinion, but when I believe something it's a manifesto?
There is also a delayed rounding (see page 7-8) used in combinatorial compression (enumerative coding).
I prefer to use blame_ninjas() myself.
Why is it that when you believe something it's an opinion, but when I believe something it's a manifesto?
I already got into these types of rounding a decade ago. For a really good read on an FPU implementation, try to find a copy of the Motorola 68881/2 Programmer's Reference Manual.
For pretty much all other cases it is broken, wrong, bad, very bad, and misguided. It is a kludge cut from the same cloth as using red and black ink, parenthesis, or location on the page (and all the permutations thereof) to indicate the sign of a number. Do not try to do any sort of scientific calculations, or engineering, or anything else that matters and round in this way.
Why? Because contrary to what some people think, there is no systematic bias in always rounding up. There are exactly as many values that will be rounded down as will be rounded up if you always round exact halves up. I think the trap that people fall into is forgetting that x.000... rounds down (they think of it as somehow "not rounding").
--MarkusQ
I worked at a large telco when Australia introduced 10% GST to replace a dizzying array of existing sales taxes and rules. I was assigned to represent the interests of our system in the company wide discussions that went on for a long time about how to handle GST rounding errors. Eventually something like this article was produced showing various rounding algorithims and their pros and cons and a mandated algorithm was given to all projects. The extreme amount of time, effort and documentation was (in my mind incorrectly) blamed on the executives ignorance of floating point limitations in computing.
The execs eventually told us they were mainly concerened that any unavoidable error should be in the customers favour...problem solved. Their downfall was not ignorance it was because they ran the meetings poorly, we were simply there to listen and answer questions. ie: They set themselves up to immediately stray out of requirements, the high level problem was forgotten and the meetings became a series of informal discussions on the wonderland of floating point. They completely missed the fact that GST was the same as existing sales taxes except for the "customer's favour and disclosure" mandates, they were way to busy tring to convert X/11 into dollars and cents.
And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
Who says it's C? The snippet might well be have been written in a language where functions can return lvalues.
quidquid latine dictum sit altum videtur.
This stuff is still important. Yes the big computers we have on our desks can do high precision floating point. but there are still some very small 4-bit and 8-bit micro controllers that controll battery chargers, control motors that move antenna on spacecraft and the control fins on air to air missles. And then there are those low-end DSP chips inside TV sets and digital cameras and camcorders.... These controllers need to do complex math using short integers and how round off errors accumulate still does matter. Remember: Not all software runs on PCs in fact _most_ software does not.
At least this Slashdot poster appears to be well-rounded.
Weeks of coding saves hours of planning.
1. ... profit!
If you, or someone else, might add all the numbers together later on, and you want them to get the right sum. Randomizing is the only way to do this if, for example, you have a list of identical numbers and you don't want to create any simulated 010101010101 pattern by alternating instead of randomizing.
Like C++, which was hinted by the assumption of a reference in the parent.
They left off one that I've used a few times when dealing with graphics, which using their naming convention would be something like "Round Toward Mean". You basically take the mean of the surrounding values in an array or matrix and then round up if the value is below the mean, and round down if it's above the mean.
It's useful for smoothing out images if you use this for each color channel (RGB, CMYK, HSV, etc.).
Famous Last Words: "hmm...wikipedia says it's edible"
I am not from Canada, I'm from Southern California.
Fantasy remains a human right; we make in our measure and in our derivative mode... -- JRR Tolkien
When wifey is in with the doctor, the husband will pick up an OB wheel we have in the waiting room. The OB wheel works sort of like a slide rule--you put one notch on when the baby was conceived, and the other notch tells you when the baby is due. Or, put one notch on when you've been told the baby is due, and the other notch will tell you when the baby was conceived. There is an important concept in that last sentence.
Guys will turn the wheel, look perplexed, ask to look at a calendar, look perplexed some more, and then approach a staff member to ask how to use the wheel, thinking they must not be using it right.
This is the point where I go hide.
I am not saying I worked for Telstra but at the time I think I was too busy minimising billing to unproductive time by sharing it amoungst customers bills. The point of the exercise was to maximise the execs bonus for "increasing productivity", the vast majority of tickets were performed for a fixed labour fee, diverting time away from the unproductive account made no difference to revenue or productivity. Soon Telstra will have what they always wanted, no workforce means everything is profit!
And did you exchange a walk on part in the war for a lead role in a cage? - Pink Floyd.
Rounding? Real men use a confidence interval anyway, so rounding is irrelevant.
Simon's Rock College
I once heard an anecdotal tale... Of an accountant, who had his wife balance the household checkbook (as a favor, so he wouldn't have to do the household paperwork as well as the paperwork from the house). 20 Years after she had been balancing the checkbook... The husband found out that she had been rounding to whole dollar amounts!!!
:)
In a hurried rush, he went through their records, and rebalanced the checkbook... After 20 years of rounding the difference he found: $.07 in their favor
Sheesh, I'm glad I'm in the U.S. AND I can file jointly with my wife (who doesn't have earned income).
You could've hired me.
You'd also note that's what I said if you actually read my post. The point was that any sort of 'set' function would pass the value. If he had made a reasonable 'getref' or just plain 'get' function we could maybe assume that it was returning a C++ reference (as you always do when overloading operators in C++).
Pete/Petri "damn, my chainsaw is clogged with 1's and 0's again." --clyde
Sheesh, I'm glad I'm in the U.S. AND I can file jointly with my wife (who doesn't have earned income).
Yeah, because the US tax laws are a paragon of fairness, transparency, and virtue.
Sorry, I'd love to talk more, but I have to run. A unicorn just flew out my ass.
it is because you never studied numerical analysis and thus dont know how computers add numbers. go to amazon and search for the book called "Numerical Methods" by Dahlquist. It is a good introduction on how computer aritmetics works.
they all give you the same issues if you just add them together. it is fundamental to how floating point works.
Try this to minimize accumulated errors during addition:
1,divide all the numbers up in positive and negative numbers.
2, sort all the positive numbers and add them together in the order of smallest first and largest last.
3, sort all the negative numbers from smallest norm first to largest and add them together in the same way.
4, then take the sum of positives and subtract it with the sum of negatives.
That book explains why you should do that.
Ok. try this then just for fun: (you will be surprised)
333333333 * 0.000000003 is 0.999999999 right?
so 1-(333333333*0.000000003) == 0.000000001 ?
float a;
int i;
a=1.0;
for(i=333333333;i>0;i--)a-=0.000000003;
printf("a:%f\n",a);
a=0.0;
for(i=333333333;i>0;i--)a+=0.000000003;
a=1.0-a;
printf("a:%f\n",a);
they are quite different right? it will all make sense after you have studies num an.
Right after they have been all listed, the USPTO will grant SCO patents on all of them!
Sent from my ASR33 using ASCII
One interesting example of mistakes with rounding errors was the Lonenz attractor which was an important part of the development of chaos thery. Lorenz first ran the simulation with one set of parameter and a few days later ran the simulation again, the original parameter values were printed out after rounding and hence different from the actual ones used. The second time he ran it he input the printed out values and came up with a very different solution. This showed the sensativity of dynamical systems to initial conditions.
There are four sorts of people in the world: fools, lunatics, idiots and morons. - Umberto Eco, Foucaut's pendulum.
I gave up assuming I knew exactly what my programs were doing right around the time I gave up writing assembly code. Actually, I gave up a little prior to that when I realised I wasn't very good as assembly code but that kind of clouds the point.
For any given high level language, the moment concepts start getting abstracted out, all kinds of false assumptions start getting made based on those assumptions.
Here's one:
Try
Before you run it, what do you figure you'll get? Please tell me you didn't honestly think you'd get 1?
If you can't even rely on floating point numbers being accurate when well within their perceived range (+/- 2^1023 to 2^-52 is not actually the same as every possible number to that degree of accuracy, despite most assumptions) then, odds are, rounding isn't going to matter that much either.
That said, at least 0.5 has the decency to fit really nicely in to binary as 2^-1 and so you can argue, with certainty, that the number you have is 0.5 before getting in to arguments about whether to round such a number up or down.
Here's one for you though...
DSP was briefly mentioned in TFA. These days, most audio is recorded in 24 bits or more, but needs to be rounded to 16 bits to master on to CD. Simple truncation can cause harmonic sounds at low levels, so a high frequency (generally inaudible) noise is added to the signal. This is called dithering, and can make audible signals that would be truncated to zero. I've heard it happen. Even stranger is that the added noise peaks at 25-30dB louder than sound you can hear.
I’m old enough to remember 16K of memory being described as “whopping”
I remember a project ages ago (before the Pentium rounding bug). The customer (a state railway company) wanted to calculate fare tables. For that, they needed to be able to round up (2.1 -> 3), down (3.9 -> 3) and commercial (2.5 -> 3). Nothing too fancy so far. However, they also needed this operation to be carried out on PARTS of a currency unit - as in $0.20. Rounding up here would mean $3.04 -> $3.20. A typical scenario would look something like this : From 1-20km, the fare is number of kilometers multiplied by .32, rounded up to the next $0.10, then multiplied with a "class factor" of 1 for second and 1.5 for first class.
(And so on, and so on...)
Calculating a complete fare table at that time would take about 12 hours on a serious size Tandem computer.
(And of course, the program was written in a mix of COBOL and FORTRAN...)
Round-half-even thing was, if I recall correctly (it's been a while), the standard algorithm used when converting a float to an integer in Visual Basic. It was one of those things that got newbies quite confused at first, since they were either used to floor()-type rounding from working in other languages or the round-half-up they learned at school.
Some floating point libraries have hacks to apply automatic rounding and avoid 'unexpected' results. However, the inaccuracy is still there, just hidden, and eventually it can grow and explode in your face.
C# presumably takes the wiser approach of making the actual value visible to the programmer.
GCHQ Quantum Insert installed. If only our tongues were made of glass, how much more careful we would be when we speak
Isn't that Square, not Round?
I encrypt all my files with Double XOR Encryption!
I should have noted in my parent post that it is not to be construed as tax or financial advice. Consult an appropriate professional for your particular case.
You could've hired me.
As the word is derived from Welsh, it's spelled 'weird', not 'wierd'....
Q: What does the "H" in Jesus H. Christ stand for? A: Haploid.
You change part of the image, and the entire image gets dithered differently.
Bad for onMouseOvers, if you didn't notice the problem in time.
I'm still trying to figure out what people mean by 'social skills' here.
Troll? Btw. the troll of phaos looks great, I made it (or at least improved on the photograph of a sculpture).
I'm still trying to figure out what people mean by 'social skills' here.