Slashdot Mirror


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."

60 of 279 comments (clear)

  1. Round this! by Anonymous Coward · · Score: 5, Funny

    1.44th post!

    1. Re:Round this! by baadger · · Score: 2, Funny

      shouldn't that be '1.44st post'...the mind is torn between math and grammar.

    2. Re:Round this! by TooFarGone · · Score: 2, Funny

      When rounding, I always look to this simple pattern:
      You spin me right round, baby Right round like a record, baby Right round round round

      It doesn't help my rounding, but it's sure is fun =)

    3. Re:Round this! by igny · · Score: 2, Interesting

      I and my friend once talked about how to own half of a penny. We came to a solution to use randomness, you flip a penny, and depending on the outcome my friend has the penny or I have it. The problem was that uncertainty is removed after the flip, and I either have it or not, and it is not quite the same as owning 1/2 penny. So for a while we flipped the penny every time we discussed the penny to keep the uncertainty.

      --
      In theory there is no difference between theory and practice. In practice there is. - Yogi Berra
  2. Most important... by T-Ranger · · Score: 5, Funny

    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.

    1. Re:Most important... by slothman32 · · Score: 5, Informative

      There's some straight line algorithm that uses a similar method.
      It keeps adding the slope value for every x increment and when it overloads it also makes the y position go up one.
      Or something like that. Bresenham's I believe.

      To get on topic I would use the usual "(x).5 to (x+1).499~9 goes to (x+1)" way.
      For negative, just ignore the sign when doing it, e.g. -1.6 -> -2

      --
      Why don't you guys have friends or journals?
    2. Re:Most important... by poopdeville · · Score: 2, Informative

      This is what significant digits are for, though significant digit arithmetic uses probability to lower rounding error instead of forcing the user to do it himself.

      --
      After all, I am strangely colored.
    3. Re:Most important... by PapayaSF · · Score: 3, Interesting
      Round down and put the extra aside. Say, in your own account.
      It's a classic computer crime/urban legend, and has been used in various films.
      --
      Q: What does the "B." in Benoit B. Mandelbrot stand for? A: Benoit B. Mandelbrot
    4. Re:Most important... by CRCulver · · Score: 4, Interesting

      Is it really an "urban legend"? As much of a trope it has become in movies with technological whizzes, Snopes says it was reported in Whiteside's Computer Capers: Tales of Electronic Thievery, Embezzlement, and Fraud , which should have the necessary citation on the case.

    5. Re:Most important... by Mr+Z · · Score: 4, Informative

      That's the basis behind delta-sigma modulation and Floyd-Steinberg dithering. You carry forward the cumulative error from previous quantization, adding it to the current term. Then you quantize as desired. Over multiple samples, the error gets spread out, such that the local average is very close to the original signal.

  3. Think you know.... by thewiz · · Score: 4, Insightful

    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"?
    1. Re:Think you know.... by Rosco+P.+Coltrane · · Score: 5, Funny

      Why would my wife being pregnant be a problem?

      You'll know 13 years from now :)

      --
      "A door is what a dog is perpetually on the wrong side of" - Ogden Nash
    2. Re:Think you know.... by v01d · · Score: 2, Funny

      If you can't carry out your 13 year old, either they need a diet or you need more excercise.

  4. my favorite rounding algorithm by User+956 · · Score: 4, Funny

    my favorite rounding algorithm is pi(r)^2.

    --
    The theory of relativity doesn't work right in Arkansas.
  5. My personal rounding program by charlesbakerharris · · Score: 5, Funny
    For rounding, I use the following:
    • Mountain Dew
    • Couch
    • Lack of willpower
    • Utter disdain for annual resolutions I made less than a week ago
    • DiGiorno's pizzas.
    Seems to work.
    1. Re:My personal rounding program by Spy+der+Mann · · Score: 3, Funny

      * DiGiorno's pizzas.

      Seems to work.


      So that's rounding towards positive infinity, right? :P

  6. Ugh by zzen · · Score: 3, Funny

    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. :)

  7. I read the first half of the article... by under_score · · Score: 5, Interesting

    ...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.

    1. Re:I read the first half of the article... by poopdeville · · Score: 2, Informative

      Banker's rounding is just a naive implementation of significant digit arithmetic. http://en.wikipedia.org/wiki/Significance_arithmet ic

      --
      After all, I am strangely colored.
    2. Re:I read the first half of the article... by pjt33 · · Score: 2, Informative

      My grandad tells me that he was taught to use round-half-even in the Royal Engineers back in WWII. One I've used which isn't in the list is stochastic rounding for all values (rather than just n+0.5) such that n+f (0 = f 1) rounds to n with probability (1-f) and (n+1) with probability f.

    3. Re:I read the first half of the article... by bill_mcgonigle · · Score: 2, Informative

      This is a great reference article! If you are programmer working with numerical algorithms, keep this article handy.

      This one too: What Every Computer Scientist Should Know About Floating-Point Arithmetic.

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
  8. What about... by Irvu · · Score: 2

    Rounding to the nearest square?

  9. Office Space by TubeSteak · · Score: 5, Funny
    PETER
    So when the subroutine compounds the interest, right, it uses all these extra decimals places that just get rounded off. So we just simplify the whole thing and we just round it down and drop the remainder into an account that we own.

    JOANNA
    So you're stealing.

    PETER
    Ah, no. No. You don't understand. It's, uh, very complicated. It's, uh, it's, it's aggregate so I'm talking about fractions of a cent that, uh, over time, they add up to a lot.
    --
    [Fuck Beta]
    o0t!
  10. floating point by BigMFC · · Score: 3, Interesting

    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.

  11. Interval arithmetic by Diomidis+Spinellis · · Score: 4, Interesting

    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.

    1. Re:Interval arithmetic by Doug+Merritt · · Score: 2, Insightful
      Using such a package can save you the trouble of performing error analysis

      Absolutely false. Let me explain that in simpler terms: wrong, wrong, wrong, wrong wrong.

      A good package will help a programmer avoid the worst problems in the simplest situations.

      The worst situations are not solvable even by human experts backed by state of the art theory.

      The bottom line is that numerical analysis is a very deep speciality, roughly like compiler design is a very deep specialty. In neither area is there some package that will solve your problems for you.

      Standard math libraries that implement functions like square root, exp, ln, etc, long ago were implemented by people like you, who didn't know nor care that those functions might be somewhat inaccurate.

      Math libraries for standard languages, for the last 20 years or so, have instead been designed and implemented by specialists who guarantee that the last bit of every result is as accurate as possible -- whereas some non-specialist like you might merely be able to guarantee that each function kind of sort of yields almost the right result, as long as "right" means maybe 16 bits of accuracy.

      Numerical analysis is a deep subject. If you aren't a specialist in the subject, you may as well shut up about it, because everything you say will be wrong, and you will spread misinformation.

      In particular, you cite an interval arithmetic package. Such things are certainly very important in numerical analysis.

      But the notion that such things completely solve all numerical analysis programs is completely laughable. Take a course in a subject before you conclude that a subject has been solved!!!

      --
      Professional Wild-Eyed Visionary
  12. Re:RIAA Rounding by slavemowgli · · Score: 3, Insightful

    Almost correct, but I think it can be simplified to the following:

    blame_pirates();
    --
    quidquid latine dictum sit altum videtur.
  13. IEEE Standard by Anonymous Coward · · Score: 4, Informative

    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

  14. Re:Applications by __aaclcg7560 · · Score: 2, Interesting

    It's called ShareBuilders. I got a dividend for a princely sum of $2.20 USD and it was re-invested for free as 0.0385 of one share. Although I wished it would round up my stock shares somtimes. I don't like seeing 27.9995 shares when it really should be 28 shares. I hate being cheated out on 0.0005 of a share. :P

  15. Re:Accounting Software by renehollan · · Score: 4, Interesting
    GST (a VAT equiv.) in Canada and QST in Quebec round UP. Always.

    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.
  16. Social Applications by Kesch · · Score: 5, Funny

    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.
  17. Slide Rules and precision by goombah99 · · Score: 5, Interesting

    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.
    1. Re:Slide Rules and precision by Detritus · · Score: 2, Interesting
      From what I recall about C on the PDP-11, single precision didn't buy you much extra speed on the FP-11 (hardware floating point unit), so why not use double precision for all floating point operations?

      See the PDP-11 Handbook (1979) for instruction timings.

      --
      Mea navis aericumbens anguillis abundat
  18. Re:Seems dumb to me by hereschenes · · Score: 2, Informative
    If you're worried about cumulative rounding error buildup, then don't round until after you've accumulated.
    As the article infers, time contraints on a system will often mean that you can't "afford" to do math as precisely as your architecture might theoretically allow you to. This is a common hurdle to overcome when you're working on embedded real-time systems: ie. the need to find a compromise between speed and accuracy. Just because you can do an operation on two floats in a loop 1000 times doesn't mean that you can afford the time to do it.
    --
    More like... nerdular nerdence!
  19. Doesn't work for negative numbers. by Anonymous Coward · · Score: 4, Insightful

    -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)

  20. you seem to be missing the point by Khashishi · · Score: 2, Insightful

    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.

  21. I was expecting something more detailed than this by Zork+the+Almighty · · Score: 2, Insightful

    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!
  22. Re:Seems dumb to me by Tim+Browse · · Score: 2, Funny

    And thus began the slide of Vegas casinos into insolvency.

  23. Re:Seems dumb to me by Jekler · · Score: 3, Interesting

    Excellent example. I've noticed in writing game systems, there's numerous situations in which rounding to the nearest is just plain wrong. Physical simulations are one area that, even in a game, is a critical issue. Round the wrong way and every object in the world behaves like it has an invisible force field around it. Another situation is that in successive bounds checking, if you we continually round in the same direction (e.g. based on a previously determined value), you end up with a bounding box that grows over time. In a real time game with values being calculated 60+ times per second, within an hour characters can't get closer than 10 feet to an object.

  24. Re:Add and truncate by Lord+Crc · · Score: 4, Interesting

    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.

    Where I'm comming from, the FPU is by default set to perform rounding, so to truncate, the FPU control word has to be modified, the move performed, and then the control word has to be restored. This makes truncating a LOT slower than rounding.

  25. Precision by Repton · · Score: 3, Informative
    for example, rounding a reasonably precise value like $3.21 to the nearest dollar would result in $3.00, which is a less precise entity.

    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.
    1. Re:Precision by thebigmacd · · Score: 2, Informative

      It's not less prescise, it's less accurate. If you are retaining 3 sig digs, rounding 3.21 to 3.00 is inaccurate. You'd be prescisely inaccurate by 0.21. Prescision != Accuracy

  26. How many times do I have to explain this by idonthack · · Score: 2, Insightful
    Compilers do not understand code if you write it as a haiku!
    </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!
    System.out.println(
    "Should I count puncutation?"
    ); // terrible haiku
    --
    Why is it that when you believe something it's an opinion, but when I believe something it's a manifesto?
  27. He missed some by Nightlight3 · · Score: 2, Interesting

    There is also a delayed rounding (see page 7-8) used in combinatorial compression (enumerative coding).

  28. Old school by Trevin · · Score: 2, Insightful

    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.

  29. Only with money in fractions by MarkusQ · · Score: 4, Informative
    "Bankers" rounding is only appropriate in a rather restricted range of problems; specifically, where you are more worried about "fairness" than about accuracy, and have a data set that is already biased towards containing exact halves (generally because you've already rounded it previously).

    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

    1. Re:Only with money in fractions by LnxAddct · · Score: 2, Insightful

      I think you might be mistaken. Round to the nearest even is statisticly significantly more accurate. Rounding halves up does nothing for accuracy as you seem to imply. Large data sets of any type of data will be biased if rounding halves up, whereas rounding to the nearest even is ever more accurate with each datapoint. Your statement about rounding to even being bad makes me think you haven't fully grasped the underlying concept, I've never seen rounding halves up used for anything in a major environment simply because it is almost always the wrong thing to use.
      Regards,
      Steve

    2. Re:Only with money in fractions by MarkusQ · · Score: 4, Insightful

      For illustration, suppose we use a floating-point format with a 10-bit mantissa. For a fixed exponent (say 0), this can represent values from 1.0 to 1 1023/1024, in 1/1024 increments. The AVERAGE of these UNROUNDED values is 1 1023/2048, which is LESS THAN 1.5. However, if all these values are rounded (with 0.5 rounding up), the AVERAGE of the ROUNDED values will be EQUAL TO 1.5, an average increase of 1/2048. Thus, this type of rounding introduces a measurable positive bias into the arithmetic.

      No, the "bias" came from your choice of data (and your unrealistic expectation that the average of a set of rounded values would equal the average of the unrounded set).

      Such examples are as easy to construct as they are misleading. Suppose we instead take the values {0.2, 0.3, and 0.5}. Their average is 1/3, and if we round them ".5 up" we wind up with {0,0,1} with exactly the same average. On the other hand, if we round them with ".5 to even" we wind up with {0,0,0} with the average of zero and an "error" (by your metric) of 100%.

      --MarkusQ

    3. Re:Only with money in fractions by MarkusQ · · Score: 3, Informative

      I think you might be mistaken. Round to the nearest even is statisticly significantly more accurate. Rounding halves up does nothing for accuracy as you seem to imply. Large data sets of any type of data will be biased if rounding halves up, whereas rounding to the nearest even is ever more accurate with each datapoint. Your statement about rounding to even being bad makes me think you haven't fully grasped the underlying concept, I've never seen rounding halves up used for anything in a major environment simply because it is almost always the wrong thing to use.

      On the contrary, I understand and have worked with this sort of thing for years. I know whereof I speak, and the situation is exactly opposite of what you claim. Specifically:

      • Round to the nearest even is statistically ssignificantly less accurate.
      • Rounding halves up is significantly more accurate.
      • Large data sets of almost any type of data will be biased if rounding to the nearest even, whereas rounding halves up is ever more accurate with each data point.

      Note that this is basically your list, with the claims reversed. So we disagree totally. Now let me explain why I am correct. First, let's review what you do when you round to the nearest integer (without loss of generality; rounding to the nearest 1/10th, or even 1/137th, is isomorphic).

      1. You start with a number which has a (potentially infinite) string of digits to the right of the decimal place
      2. You drop (truncate) all but one of the unwanted digits.
      3. You conditionally change the lowest order digit you intend to keep
        • For "round up" you add one to it if the remaining unwanted digit is 5,6,7,8, or 9
        • For "round to nearest even" you add one to it if the remaining unwanted digit is 6,7,8, or 9, or if it is odd and the remaining unwanted digit is five.
      4. You drop the remaining unwanted digit

      Note that the only difference in results between these rules comes from numbers where:

      • The last digit to be kept is even and
      • The first of the digits to be disposed of is 5

      For example, the number 4.56106531 would be rounded to 4 in the "nearest even" case or to 5 in the "round up" case But clearly, the "nearest even" result is less accurate, and introduces a significant bias. 4.56106531 is closer to 5 than to 4, and should be rounded up. Always.

      At this point, you may object that you aren't planning on truncating before you apply the rule (or, equivalently, you only do the even odd dance on "exact" halves). But how did you get an "exact" half? Unless you have infinite precision floating point hardware, less significant bits fell off the bottom of your number; unless they were all zero your "exact half" is the result of truncation and the above logic still applies.

      The only common case where it doesn't apply is (as I stated originally) when dealing with money, where 1) your sample is biased to contain "exact halves" and 2) it is more important to be "fair" than it is to be accurate. This, in any case, is more of a convention than a fact of mathematics; we agree that money is tracted to a certain point and ignore the half pennies owed and the $0.00004537531 of interest due on them; if we didn't even money would not be an exception to the logic above.

      -- MarkusQ

    4. Re:Only with money in fractions by wildsurf · · Score: 2, Informative

      No, the "bias" came from your choice of data (and your unrealistic expectation that the average of a set of rounded values would equal the average of the unrounded set). Such examples are as easy to construct as they are misleading. Suppose we instead take the values {0.2, 0.3, and 0.5}. Their average is 1/3, and if we round them ".5 up" we wind up with {0,0,1} with exactly the same average. On the other hand, if we round them with ".5 to even" we wind up with {0,0,0} with the average of zero and an "error" (by your metric) of 100%.

      Your example proves my point. Which distribution is more arbitrary; "Arithmetically uniform," or the set "{0.2, 0.3, and 0.5}"?

      To be sure, if the distribution is, for example, geometrically uniform (i.e., uniformly distributed exponents), then Benford's Law applies, and significantly more values in the range [0..10] (say) will have fractions less than 0.5. This effect decreases dramatically for large values, since the fractional component (which is what we care about) shifts to less and less significant bits. But If you find yourself rounding lots of very small values to integer, then your loss of precision will far exceed the error caused by your 0.5-rounding choice, and you should probably rethink what you're doing.

      In typical real-life scenarios, it's logical to assume that your set of numbers will have a reasonably smooth distribution (arithmetically uniform or not), and also that most values will be considerably larger than the rounding granularity. (Dollar values in the $10-$100 range rounded to pennies, for example.) Any such distribution will approach arithmetic uniformity at the scale of the rounding granularity (pennies). Hence, the choice of an arithmetically uniform distribution between successive integers is NOT arbitrary, and accurately represents most real-life distributions. For such distributions, the 0.5->1 rounding convention introduces a small but measurable positive bias.

      --
      Weeks of coding saves hours of planning.
    5. Re:Only with money in fractions by mesterha · · Score: 2, Insightful

      For example, the number 4.56106531 would be rounded to 4 in the "nearest even" case or to 5 in the "round up" case But clearly, the "nearest even" result is less accurate, and introduces a significant bias. 4.56106531 is closer to 5 than to 4, and should be rounded up. Always.

      This is the wrong rule. The number 4.56106531 would be rounded to 5 with both techniques. The "nearest even" technique for rounding to the nearest integer only applies to 4.50000000. In this case, you would round the number to 4. You might say what's the point, since this is a very unlikely case. However, if you only have two digits to work with it becomes much more significant.

      At this point, you may object that you aren't planning on truncating before you apply the rule (or, equivalently, you only do the even odd dance on "exact" halves). But how did you get an "exact" half? Unless you have infinite precision floating point hardware, less significant bits fell off the bottom of your number; unless they were all zero your "exact half" is the result of truncation and the above logic still applies.

      The "exact half", for all you know might be below .5 or might be above .5. You seem to be assuming it is the result of truncating a single number. The rounding occurs during arithmetic operations and, for all you know, the real extra is just as likely to be below .5 as it is above .5. That's the essence of rounding and why we don't use truncation.

      But just for fun, lets take the case where you are inputing the number into the computer. If the number has a number of significant digits more than the machine then for most problems the number is just as likely to be a little below the given number as it is above, therefore you should use "nearest even" to remove bias. If the number has a number of significant digits less than or equal to the machine, you just enter the number.

      As an rough argument why "nearest even" works, every time you do an arithmetic operation with rounded numbers the new number is just as likely to be a little too big as it is to be a little too small. (This is why we represent rounded number as x*(1 + or - epsilon).) Therefore rounding 1.0 to 1 is ideal since the number is just a likely to be a little smaller as it is to being a little bigger. Rounding 1.1 to 1 starts introducing bias since you are shrinking the number. However, the bias for 1.1 balances out the bias for 1.9, and the bias for 1.2 balances out the bias for 1.8. However, if you continue, the bias for 1.5 is not balanced out and the sum of numbers tends to grow. One way around this is to flip a coin for 1.5 and round up half the time and down the other half. This is expensive, so a cheap alternative is to just use the next digit as the random coin; round up if it's odd and round down if it's even..

      Last, as an appeal to experts, Reiser and Knuth [1975] disagree with you. In fact, Knuth has a write up in one of his Art of Programming books on the issue. A short but online explanation can be found here in the section Exactly Rounded Operations.

      --

      Chris Mesterharm
    6. Re:Only with money in fractions by mesterha · · Score: 2, Informative
      The source you cite (and, it appears, your arguments, at least implicitly) are talking about how to deal with repeated rounding in calculations with a single guard digit. As the Knuth paper clearly states in the introduction to the defense of round-ties-to-even:

      Incorrect. Did you read the article? The rest of your quote from the article is

      The example immediately preceding Theorem 2 shows that a single guard digit will not always give exactly rounded results. The previous section gave several examples of algorithms that require a guard digit in order to work properly. This section gives examples of algorithms that require exact rounding.

      so it has nothing to do with guard digits. In fact, they then go on to define rounding, since at this point it hasn't been formally defined. After they give the rounding to even definition, they justify the definition with a theorem from Reiser and Knuth. Note, the webpage is not a paper from Knuth; it is from David Goldberg. Goldberg then gives an example to show how rounding up can introduce bias in a way that rounding to even can not. Last they consider the issue closed and assume rounding to even for the rest of the paper.

      On the more general case, the only mention corresponds to my position:

      ...double-rounding only produces an incorrectly rounded result when the second rounding is determined by the round-ties-to-even rule...

      This is not a more general case. They are talking about a precise type of problem called double-rounding that comes from mixing double precision and extended double precision calculations. Furthermore they don't talk about rounding up as a solution to this problem.

      It's clear you just did some simple searches of the article to try and support your position. I suggest you read some of the article. Notice it's title, "What Every Computer Scientist Should Know About Floating-Point Arithmetic".

      --

      Chris Mesterharm
  30. Re:Accounting Software by TapeCutter · · Score: 2, Interesting

    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.
  31. This stuff is still matters by ChrisA90278 · · Score: 3, Insightful

    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.

  32. Round Toward Mean? by miyako · · Score: 3, Informative

    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"
  33. Rounding? by students · · Score: 2, Funny

    Rounding? Real men use a confidence interval anyway, so rounding is irrelevant.

  34. Re:that's rounding up by Sarisar · · Score: 3, Interesting

    I know you're joking, but where I used to work (a large multinational financial institution, well insurance company) they almost always simply truncated or rounded up to make them end up with more money that way.

    One exception was for when people were making payments into a pension scheme because there were exceedingly strict government rules about what to do. Although I forget the details now, but something about putting a percentage of your salary into the pension scheme we couldn't take MORE so we had to truncate then, otherwise if they wanted to put in 2% salary and we took 2.000001% they could sue us over it or something.

    I also remember a maths teacher pointing out why interest is paid monthly on what you have in the account at the beginning of the month, otherwise you could make money by taking your money out and putting it back in every day, or hour, or minute if they calculated it that way (just check for yourself it you want!)

  35. I never thought I knew what was happening... by nick_davison · · Score: 2, Interesting
    It's a good read, especially if you *think* you know what your programs are doing.

    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

    public class massiveadd {

            public static void main(String[] args) {
                    double a=0.001;
                    double b=0;
                    for (int i=0; i<1000; i++) {
                            b+=a;
                    }
                    System.out.println(b);
            }
    }
    ..or the equivalent in your language of choice.

    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...


    double a=0.001;
    double b=0;
    for (int i=0; i

    Except what should be 0.5 has now wandered off to 0.5000000000000003 and even if you do try rounding point fives down, it's now greater than 0.5 anyway - so you'll get one instead of zero...

    Which raises the argument - just because you happen to be passing 0.5 in to your rounding function and are arguing which way it should go, what on earth makes you think 0.5 is the correct value of whatever you were working with anyway?

    The point of all of this being that these things are cool concepts to know to show off at nerd cocktail parties (OK, over a D&D game is more likely) but open a whole can of worms if you actually want to get authoratative on the subject as one assumption getting questioned leads to another and another. For a very few, it's worth discovering all of the many variants - which likely requires an indepth knowledge of how the compiler works and you're back at assembler anyway. For everyone else, beyond the nerd show off, it's about degrees of comfort and, in most cases, that degree is... leave the lid on the can and back away slowly.

    And that leaves me where I am. I'm aware that there're concepts like which way rounding goes, what happens with small decimals, etc. and, luckily for me, I'm in a field where thorough testing is considered accurate enough. Actually freaking out about such issues just feels like coder OCD.
  36. Also important in audio by ockegheim · · Score: 2, Interesting

    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”
  37. That is nothing... by McSnarf · · Score: 2, Interesting

    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...)