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

279 comments

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

    1.44th post!

    1. Re:Round this! by Anonymous Coward · · Score: 0

      1.54th post!

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

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

    3. Re:Round this! by Killall+-9+Bash · · Score: 1

      one point fourty-fourst? If you're going to be a grammar nazi, at least be right.

      --
      "Prediction: within 10 years, Windows will be a Linux distribution." Me, 7-6-2016
    4. Re:Round this! by Jussi+K.+Kojootti · · Score: 1

      ...WHOOSH!

    5. Re:Round this! by ModMeFlamebait · · Score: 1

      1.44nd?

      --
      Pavlov. Does this name ring a bell?
    6. 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 =)

    7. 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
    8. Re:Round this! by Anonymous Coward · · Score: 0

      What you need to do is get the penny in one of two boxes in such a way that you can't detect which one it's in, and each of you take a box. Since there's an equal probability of it being in either box, and you don't know which it's in, you each have half a penny. Or more precisely, an entangled state where a penny is both there and not there. (maybe Schrödinger's cat really choked on the half-penny)

      As a physics major, I really hate quantem mechanics because of this stuff.

  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 darthservo · · Score: 1

      Just don't put the decimal point in the wrong place...

      --

      Prove it.

    2. Re:Most important... by Reziac · · Score: 1

      Meant as a joke, but... I vaguely remember being taught a system in grade school, where cumulative roundoff errors were reduced somewhat by combining the total number of roundoffs, and rounding the main product up or down one or more units depending on whether you'd rounded up or down more in the sub-units. I don't recall the exact system but it does work as a method in everyday life.

      --
      ~REZ~ #43301. Who'd fake being me anyway?
    3. Re:Most important... by suso · · Score: 1

      And don't forget the cover sheet on your TPS report.

    4. 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?
    5. 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.
    6. 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
    7. 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.

    8. Re:Most important... by Khashishi · · Score: 1

      yeah but you might get caught and end up in pound-you-in-the-ass penitentiary

    9. Re:Most important... by ClamIAm · · Score: 1, Funny
      Gulp-n-Blow.

      There has to be a joke here, I know there does.

    10. Re:Most important... by Anonymous Coward · · Score: 0

      I did that once... crashed my old computer in the progress...

    11. Re:Most important... by citizenr · · Score: 0

      Simpsons

      --
      Who logs in to gdm? Not I, said the duck.
    12. Re:Most important... by Reziac · · Score: 1

      Oh yes, I knew there was a term for it... I last thought seriously about math 30 years ago, and while the concepts remain, all the details have, ah, been rounded off by my brain :)

      --
      ~REZ~ #43301. Who'd fake being me anyway?
    13. Re:Most important... by Reziac · · Score: 1

      Interesting! And now my brain (which in another post I accuse of rounding off old data) ...hurts. :)

      --
      ~REZ~ #43301. Who'd fake being me anyway?
    14. 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.

    15. Re:Most important... by Reziac · · Score: 1

      Oh! Good info. You've just radically improved my grok of dithering. (IANAMathematician. :)

      --
      ~REZ~ #43301. Who'd fake being me anyway?
    16. Re:Most important... by pthisis · · Score: 1

      An urban legend doesn't have to be false. From the alt.folklore.urban FAQ:

      An urban legend does not have to be false, although most are. ULs often have a basis in fact, but it's their life after-the-fact (particularly in reference to the second and third points) that gives them particular interest.

      See also the 'A Digression On Urban Legends And "Falsehood"' section of that FAQ (which also contains similar quotes from authors of published books on urban legends).

      --
      rage, rage against the dying of the light
    17. Re:Most important... by AndrewStephens · · Score: 1

      I don't have a cite, but I have been told that several schemes like this have been carried out over the years. The problem is that there is really no way to pass off several hundred thousand transactions for less than a cent as legitimate. Banks tend to notice that kind of thing.

      --
      sheep.horse - does not contain information on sheep or horses.
  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: 1

      Come to think of it, I could say the samething about my wife.

      If your wife is getting rounded, I'd say she's either pregnant or bulimic. Either way, you have a problem.

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

      Why would my wife being pregnant be a problem?

    3. 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
    4. Re:Think you know.... by Anonymous Coward · · Score: 0

      Better yet... Why would she be getting rounded if she were bulimic?

    5. Re:Think you know.... by Flimzy · · Score: 1

      Just remember... your wif^H^H^Hcomputer always does _exactly_ what you tell it to do...

    6. Re:Think you know.... by gardyloo · · Score: 1

      GIGO

    7. Re:Think you know.... by Joe5678 · · Score: 1

      Better yet... Why would she be getting rounded if she were bulimic?

      I'm guessing that would be rounding *down*

    8. Re:Think you know.... by rvw14 · · Score: 1

      It will be 7-8 years, as my oldest daughter is 5 right now. I hope this next one is a boy.

    9. Re:Think you know.... by birge · · Score: 1
      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 you've been trying to program your wife for 25 years, I think I may see your problem...

    10. Re:Think you know.... by mrhartwig · · Score: 1
      You'll know 13 years from now :)

      Unless he finds out 2 years from now. Or when the kid goes to school & starts learning new, exciting, ways to interact with his/her peers, parents, and siblings. Or at various other un-fun stages of development.

      otoh, it's all worth it when A) your 2-year old runs screaming "Daddy" & hugs you when you get home from work; B) when the kid turns into a mature human; and C) when you're presented with grandkids, and you get to hand them back when they have dirty diapers. And a whole bunch of other times, too.

      Do you know the difference between a 2-year old & a 13-year old?

      When the 2-year old throws a tantrum in the grocery store, you can pick them up & carry them out.

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

    12. Re:Think you know.... by Threni · · Score: 1

      > I hope this next one is a boy.

      If the hospital ask you if you want to know then it's probably a boy.

    13. Re:Think you know.... by Lars+T. · · Score: 1

      Even if you can pick up thirteen year old, he can still hit vital parts.

      --

      Lars T.

      To the guy who modded me down from perfect to terrible Karma - Apple haters still suck

    14. Re:Think you know.... by WasteOfAmmo · · Score: 1
      If you can't carry out your 13 year old, either they need a diet or you need more excercise.[yep, I laughed when I read this too, but...]

      My soon to be 13 year old is currently 2 shoe sizes larger then me, 1.5" taller and within 60 lbs of me (ya I should be about 40 lbs lighter). I can still lift him but carrying him far while he is throwing a tantrum would be a job and a half. Dead weight over my shoulder I can still carry him a fair distance though. I don't expect to be able to test that after he gets his next few martial arts belts :)

      Merlin.

    15. Re:Think you know.... by Mr.+Slippery · · Score: 1
      I don't expect to be able to test that after he gets his next few martial arts belts :)

      You could sign up and take class with him. It'll help with that extra 40 pounds, and martial arts training is one of the few athletic activities that parents and kids can do together. We have several families where one of the parents trains along with one (or more!) of the kids, and they seem to get a lot out of it.

      --
      Tom Swiss | the infamous tms | my blog
      You cannot wash away blood with blood
  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.
    1. Re:my favorite rounding algorithm by Anonymous Coward · · Score: 0

      I think you're looking for x^2 + y^2 = r^2.

    2. Re:my favorite rounding algorithm by Anonymous Coward · · Score: 0

      In Alabama, Pi=3.

  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

    2. Re:My personal rounding program by Anonymous Coward · · Score: 0

      It's not DiGiorno's, it's Delissio! Or is it delivery? Who cares...

  6. Re:offtopic by jeblucas · · Score: 1, Funny

    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.
  7. Chuck Wagon. by Anonymous Coward · · Score: 0

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

    Hey! Were's ground round on that list?

  8. Re:Just avoid the problem entirely by Anonymous Coward · · Score: 0

    In fact, why not just do everything in binary? "after all the computer itself does"!

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

  10. Don't you just... by TedTschopp · · Score: 0, Offtopic

    Double it and add Thirty, or is that the metric conversion for Beer?

    --
    Fantasy remains a human right; we make in our measure and in our derivative mode... -- JRR Tolkien
    1. Re:Don't you just... by baadger · · Score: 1, Offtopic

      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

    2. Re:Don't you just... by immanis · · Score: 1

      *buys TedTschopp 42 metric beers* It's a bloody shame no one recognized the reference.

    3. Re:Don't you just... by brunson · · Score: 0, Offtopic

      And you have no idea who Bob and Doug McKenzie are.

      Please stop posting until you acquire a sense of humor.

      --
      09F911029D74E35BD84156C5635688C0
      Jesus loves you, I think you suck
  11. RIAA Rounding by ackthpt · · Score: 0, Flamebait

    RIAA method:
    if (sales(type_cd,2005) < sales(type_cd,2004)) {
    set_sales(type_cd,2005)=0;
    blame_pirates();
    }

    --

    A feeling of having made the same mistake before: Deja Foobar
    1. 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.
    2. Re:RIAA Rounding by Anonymous Coward · · Score: 1, Funny
      RIAA method:
      if (sales(type_cd,2005) < sales(type_cd,2004)) {
      set_sales(type_cd,2005)=0;
      blame_pirates();
      }


      Really? I thought it was more like:
      if (sales(type_cd,2005) <= sales(type_cd,2004)) {
        set_sales(type_cd,2005,0);
      }
      else {
        set_projected_sales(type_cd,2005,sales(type_cd,200 5)*2);
      }
      blame_pirates();
    3. Re:RIAA Rounding by PetriBORG · · Score: 1

      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
    4. Re:RIAA Rounding by Anonymous Coward · · Score: 0
      Bzz, compiler error, assignement without left-hand argument. Wow thats a horrible piece of code.

      Not in my horrible compiler, I can do this sort of crap, which isn't a very comforting thought.

    5. Re:RIAA Rounding by slavemowgli · · Score: 1

      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.
    6. Re:RIAA Rounding by cnettel · · Score: 1

      Like C++, which was hinted by the assumption of a reference in the parent.

    7. Re:RIAA Rounding by PetriBORG · · Score: 1

      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
    8. Re:RIAA Rounding by Fresnik · · Score: 0

      For a second there I thought you were talking about the Church of the Flying Spaghetti Monster.

  12. The best rounding algorithm... by Anonymous Coward · · Score: 0

    ...is the round-spam-spam-random-spam-round algorithm.

  13. 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 tepples · · Score: 1

      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 (with f in [0 .. 1) ) rounds to n with probability (1-f) and (n+1) with probability f.

      That method is also called "dithering", and most finer signal processing algorithms and analog-to-digital converters use it to preserve overall system linearity.

    4. 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)
    5. Re:I read the first half of the article... by thdexter · · Score: 1

      Geez, with your post title ("I read the first half of the article") I figured you were going to say you rounded down and hadn't read any. You missed a golden opportunity, bub.

      --
      I'm on a road shaped like a figure eight; I'm going nowhere but I'm guaranteed to be late.
    6. Re:I read the first half of the article... by cffrost · · Score: 1


      This method is also employed in marine navigation (e.g., speeds, headings, distances, coordinates).

      The intent here is to speed the calculation of time-sensitive solutions. Time is saved mostly by eliminating odd numerators, which tend to slow manual division.

      --
      Thank you, Edward Snowden.

      "Arguments from authority are worthless." —Carl Sagan
  14. What about... by Irvu · · Score: 2

    Rounding to the nearest square?

    1. Re:What about... by sld126 · · Score: 1

      Or the nearest prime...

      --
      You're just jealous because the voices only talk to me.
    2. Re:What about... by wcleveland · · Score: 0

      and what about rounding to the nearest prime?

    3. Re:What about... by jonadab · · Score: 1

      > Rounding to the nearest square?

      How about rounding to the nearest number that is the natural logarithm of a perfect square?

      --
      Cut that out, or I will ship you to Norilsk in a box.
  15. Add and truncate by RackinFrackin · · Score: 1, Flamebait

    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.

    1. Re:Add and truncate by ztransform · · Score: 1

      I'm quite impressed, I never thought about using this method until you mentioned it!

    2. Re:Add and truncate by RackinFrackin · · Score: 1

      I thought it was pretty slick too. I think that one of my professors mentioned it to me when I was in college.

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

    4. Re:Add and truncate by quokkapox · · Score: 1
      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. -- POKE 53281,0 POKE 53280,0

      The 6510 wasn't THAT slow.

      --
      it's a blue bright blue Saturday hey hey
    5. Re:Add and truncate by tmasssey · · Score: 1
      Just like every BASIC random-number-generator:

      x=INT(RND(0)*6+.5)

      For integers from 1 to 6 inclusive.

      Given your signature, I figured you would have learned that *long* before college...

    6. Re:Add and truncate by RackinFrackin · · Score: 1

      How is this flamebait?

    7. Re:Add and truncate by jonadab · · Score: 1

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

      I would think that an optimizing compiler could do better than this. Truncating ought to take at most two instructions at the machine level, and, assuming there is a register large enough to hold the data type in question, there shouldn't be any moving necessary. Assuming the number is stored in two's complement form, which is usual, two shift operations will do it. For a floating-point number you do have to calculate how many bits to shift off, based on the magnitude, but this should not be a slow operation, and definitely should not be "a lot slower" than rounding.

      Of course, if the FPU is optimized to do rounding quickly, add-and-truncate may not actually *gain* you much, but it shouldn't be a performance *problem*, either.

      I prefer to use a high-level language's rounding routine and let the compiler jocks figure out how to optimize it. Of course, people who are designing hardware-based rounding like in the article don't have that option available to them.

      --
      Cut that out, or I will ship you to Norilsk in a box.
  16. Computer games should use floor(x+rand()) by RedLaggedTeut · · Score: 1, Troll

    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.
  17. Rounding can be really annoying. by Anonymous Coward · · Score: 0

    When you multiply and divide you often end up truncating/rounding whether you intend to or not. You just don't have enough bits for the precision you need. If you have enough operations, you can end up with some significant errors. That's why DSPs have double wide busses internally.

    My own problem was creating a bunch of multiple choice student questions and neglecting to account for the truncation that resulted when I displayed the numbers. Needless to say, the students were annoyed when none of the answers were exactly what they calculated.

  18. 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!
    1. Re:Office Space by Anonymous Coward · · Score: 0

      Wasn't that how Richard Pryor got himself in trouble in one of the superman movies as well?

    2. Re:Office Space by naelurec · · Score: 1

      PETER: Well, how does it work?

      MICHAEL: It's pretty brilliant. What it does is where there's a bank
      transaction, and the interests are computed in the thousands a day in
      fractions of a cent, which it usually rounds off. What this does is it
      takes those remainders and puts it into your account.

      PETER: This sounds familiar.

      MICHAEL: Yeah. They did this in Superman III.

      PETER: Yeah. What a good movie.

    3. Re:Office Space by Claire-plus-plus · · Score: 1

      the same trick was done in Superman 2 or course. By that trained-on-the-job programmer played by Richard Prior (I think). I am still amazed that a programmer trained on the job would think of that!

      --
      99 bottles of beer in 175 characte
    4. Re:Office Space by EvanED · · Score: 1

      Superman III, not II.

      Supes 2 was the one with the three Krypton criminals introduced at the beginning of Superman I then left -- Ursa, Non, and (General) Zod -- who come to Earth and wreak havoc until Clark restores his Superman superpowers he gave up for Lois and fights them, and was actually pretty good.

      3 was with Richard Pryor and the red kryptonite and the self-learning computer and red kryptonite that causes Superman to act evil, and was pretty mediocre.

      4 was with the nuclear man dude Luther created, and was an insult to the word "movie" and "Superman".

    5. Re:Office Space by bill_mcgonigle · · Score: 1

      Supes 2 was the one with the three Krypton criminals introduced at the beginning of Superman I then left

      Supposedly the original story was both movies, but they editied for time.

      3 was with Richard Pryor and the red kryptonite and the self-learning computer and red kryptonite that causes Superman to act evil, and was pretty mediocre.

      In a just world they'd have a Director's Cut with Richard Pryor actually doing his act. Rated R for Language, naturally.

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    6. Re:Office Space by jgrahn · · Score: 1
      the same trick was done in Superman 2 or course. By that trained-on-the-job programmer played by Richard Prior (I think).

      Richard Pryor. Who died last month, by the way.

      I am still amazed that a programmer trained on the job would think of that!

      Wasn't he supposed to have a hidden talent for programming, though? I liked that part -- the idea that it's talent that makes great programmers, not fancy education. Or a light complexion.

    7. Re:Office Space by Hal_Porter · · Score: 1
      I liked

      Peter Gibbons: Doesn't it bother you that you have to get up in the morning and you have to put on a bunch of pieces of flair?
      Joanna: Yeah, but I'm not about to go in and start taking money from the register.
      Peter Gibbons: Well, maybe you should. You know, the Nazis had pieces of flair that they made the Jews wear.
      Joanna: What???
      Peter Gibbons: Nothing.

      Strange but true, Godwin's Law was first stated in 1990, but in 1950, Leo Strauss said


      "In following this movement towards its end we shall inevitably reach a point beyond which the scene is darkened by the shadow of Hitler. Unfortunately, it does not go without saying that in our examination we must avoid the fallacy that in the last decades has frequently been used as a substitute for the reductio ad absurdum: the reductio ad Hitlerum. A view is not refuted by the fact that it happens to have been shared by Hitler."


      Not only did he invent the concept 40 years before Godwin, he invented the wonderful cod Latin phrase Reduction ad Hitlerum, or "Reduction to Hitler", a jokey reference to Reductio ad absurdum
      --
      echo -e 'global _start\n _start:\n mov eax, 2\n int 80h\n jmp _start' > a.asm; nasm a.asm -f elf; ld a.o -o a;
  19. Applications by ch-chuck · · Score: 1

    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); }
    1. 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

    2. Re:Applications by ytm · · Score: 1

      Banking accounting programmers should already know that you can't store and calculate on decimal fractions accurately using binary floating point numbers. It's not a big deal to write a decimal arithmetic class on your own, but first - you have to be aware of the problem.

  20. Accounting Software by Anonymous Coward · · Score: 0

    One of my perennial complaints against accounting software (at least here in Britain) is that they round half pennies differently from the government's rules on Value Added Tax. So someone buying by mail order who sends a cheque for £25 plus 17.5% VAT rounds down (correctly) and the **** accounts program generates an invoice rounding up (incorrectly) and I am for ever writing an invoice with an extra 1p line to correct the error.

    1. 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.
    2. Re:Accounting Software by pkhuong · · Score: 1

      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
    3. 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.
    4. Re:Accounting Software by Achromatic1978 · · Score: 1
      Did you also notice that when everyone was being told to round the final result to the nearest 5 cents, Telstra took that opportunity to round every local call to the nearest 5 cents?

      1. ... profit!

    5. Re:Accounting Software by TapeCutter · · Score: 1

      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.
    6. Re:Accounting Software by renehollan · · Score: 1
      And don't forget the income surtax: the various provinces and the feds tax the income tax you pay over a certain amount in a progressive fashion. Most places it's 5% of the first $5000 tax over $5000, and 10% of the rest, or something like that.

      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.
    7. Re:Accounting Software by Karma+Farmer · · Score: 1

      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.

    8. Re:Accounting Software by renehollan · · Score: 0, Offtopic
      "Yeah, because the US tax laws are a paragon of fairness, transparency, and virtue."

      While the U.S. tax code might be rather baroque, my individual experience with the IRS has been far better than any experience I had with Revenue Quebec -- and I've had hideously complex tax returns sometimes requiring the services of a tax accountant at a cost of $700 to file 1 inch thick returns.

      Before y'all scream "See, I told you so!" note that the complexity was of my doing: Moving expenses are handled differently in the U.S. than Canada, and when I returned to the U.S. after working for a Canadian employer that had paid my relo expenses and required two years employment or a refund of a prorated portion of those expenses, I used complex tax treaties to make them deductible against U.S. taxes in the year I refunded them.

      In Canada, moving expenses are neither a taxable benefit when reimbursed, nor a deduction when not. But, the situation in the U.S. is different: reimbursed moving expenses (for purposes of employment, satisfying the time and distance tests) are taxable, but are also deductible to the extent they were used to pay for elegible moving expenses related to employment. The practical upshot is that if you pay net moving expenses related to a new job, you can claim them as an itemized deduction against income in the year you move, or the year you pay them. Refunding reimbursed moving expenses makes them deductible in the year you refund them -- if you are subject to U.S. taxes during the period of employment.

      For a U.S. citizen, this is trivial: they are always taxed on worldwide income, regardless of where they reside, though there is a blanket $US70k exemption for periods of residency outside the U.S. exceeding one calendar year. But, I am a Canadian, not U.S. citizen, and failed to meet the U.S. Tax residency test when i was in Canada.

      This is where the tax treaties come in.

      The Canada-U.S. Tax Treaty basically means that a Canadian, in the U.S., can't be taxed more than an American in similar circumstances. It also says that a Canadian can not be subject to greater U.S. taxes than a different foreigner under similar circumstances. This is where the U.S.-Germany Tax Treaty comes in: A German can't be taxed worse, anywhere in the world than an American in similar circumstances. So, a German, in Canada, can't be subject to greater U.S. taxes than an American in Canada would, and thus a Canadian, in Canada, can't be subject to greater U.S. taxes than that German, or an American.

      The practical upshot is that a Canadian, in Canada, can elect to subject themselves to U.S. taxation as if they were an American in Canada. Generally, there is little benefit to do this, because all you'd do is use the FEIE to excempt the first US$70k (or is it $80k now?) of employment income, and/or use the FTC to offset U.S. tax owing by Canadian tax paid (which will likely be higher), yielding the same result as not subjecting one's self to U.S. taxes in the first place: there are few U.S. refundable tax credits. (One is the child tax credit, which, by treaty, is not taxable in Canada, because it is not taxable in the U.S. so Canadians with kids can pull a fast one on Uncle Sam if they have a good tax accountant).

      Sometimes, however, if you have U.S. source income (you just got a NAFTA visa), it can pay to ammend one's U.S. return for prior years in Canada, and subject one's self to U.S. tax for them (which should be a wash, as noted above) in order to get current benefits relating to the earning of that prior-years income, i.e. a deduction for the moving expenses paid to return to Canada to earn it.

      Of course, if you do this, you have to declare all foreign source income. That means gains on the sale of Canadian property (which might be exempt, but gains on the discharge of a foreign mortgage with cheaper U.S. dollars than when the mortgage was written aren't), bank interest, etc. You also get to deduct mortgage interest,

      --
      You could've hired me.
  21. Don't round much myself by FirstTimeCaller · · Score: 1

    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:

    #define DIV_ROUNDUP(n, d) ((n)+((d)-1))/(d))
    --
    Wanted: witty unique signature. Must be willing to relocate.
    1. Re:Don't round much myself by LukeWink · · Score: 1

      That code doesn't even compile, let alone work.

    2. Re:Don't round much myself by dtfarmer · · Score: 1
      #define DIV_ROUNDUP(n, d) (((n)+((d)-1))/(d))
    3. Re:Don't round much myself by Anonymous Coward · · Score: 0

      rounding up to nearest integer value

      That's a new one to me.

  22. Seems dumb to me by n6kuy · · Score: 1

    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.
    1. Re:Seems dumb to me by Anonymous Coward · · Score: 0

      You know what seems dumb to me? You. The whole point is what happens at X.5, which has no "nearest."

    2. Re:Seems dumb to me by n6kuy · · Score: 1

      But if you just accumulate the 0.5 instead of discarding it, then there is no "what do you do with it?" involved.

      --
      If you disagree with me on social issues, then it's pretty clear that you are a narrow-minded bigot.
    3. Re:Seems dumb to me by jackb_guppy · · Score: 1

      Becuase over time the error become to big.

      In Casinos, when "counting" a change in a machine, they use rounding.
      The wieght the money (not count it).
      Multiple with the exchange factor (100lb = $133.34 in Pennies).
      Round the amount with allernating Round-Up / Round-Down on seccuessive wieghings for the machine.

      This way over time the rounding error will tend to average to 0.

    4. Re:Seems dumb to me by Anonymous Coward · · Score: 0

      RTFA. Many of the algorithms mentioned are designed simply to deal with the .5 case, where rounding up or down is equally valid depending on your application. Round half even is particularly nifty in that it is designed to make frequent roundoffs of a .5 have less of an impact on the error.

      Also, keep in mind, there isn't infinite precision. Many of these rounding strategies are employed in the implementation of floating point numbers, so with very precise decimals or very large numbers with smaller decimals, rounding occurs whether you want it or not. Doesn't matter much to most people, but for scientific purposes on macro- or micro- scales, the rounding matters more.

      -ShadowRanger

    5. Re:Seems dumb to me by Boronx · · Score: 1

      This means we can condition the casinos to better the odds on the machines by using weighted coins.

    6. Re:Seems dumb to me by Anonymous Coward · · Score: 0

      >Why not just round to the nearest in all cases?

      I understand that there are cases where doing that skews the distribution in a poorly representative way, where different rounding methods lead to more accurate overall results.

    7. Re:Seems dumb to me by ChadN · · Score: 1

      Ah, but what if you have 0.49999999999999999999999999999999999999999999999, or any other number that just can't fit exactly into an n-bit floating or fixed point system? At that point, you are forced to do some kind of rounding, giving you a small error, and those small errors accumulate as the number of arithmetic operations increase.

      Yes, for certain types of numerical problems, there is a bounded precision, or set of values, for which you could create a specialized counting system (ie. many financial problems are more amenable to fixed point operations); for most everything else, there is floating point, hence non-exact numerical representations, hence rounding (at EACH operation!).

      --
      "It's overkill, of course. But you can never have too much overkill." - Anonymous Slashdot Coward
    8. Re:Seems dumb to me by fishbowl · · Score: 1


      >In Casinos, when "counting" a change in a machine, they use rounding.

      It is very hard to find a Las Vegas casino that still has any coin operated slot machines. This one thing has eliminated my gambling habit completely. I have relatives in Las Vegas and visit often. I typically take a few rolls of quarters, "slot machine money", for the sole purpose of throwing it away. Guess what? One trip, I showed up with my rolls of quarters -- AND THEY DON'T HAVE COIN OPERATED MACHINES ANYMORE!

      I'll be damned if I'm going to go to the trouble of standing in line to buy a token card just for the privilege of throwing away my spare change.

      --
      -fb Everything not expressly forbidden is now mandatory.
    9. Re:Seems dumb to me by Anonymous Coward · · Score: 0

      > Why not just round to the nearest in all cases?

      You might want to round down in some cases . . .

      You have 13 marbles. There and 5 kids. How many marbles can give to each kid?

    10. Re:Seems dumb to me by webjonesin · · Score: 1

      Because in a computer you are dealing with an internal representation that is always finite...where as in the world of abstractions you can work with infinite precision numbers...

      As it turns out...that loss of precision can actually impact the way your calculations work.

      The correctness of the result of a calculation can even be impacted by the order in which the calculation is done. (this can and has resulted in things going BOOM)

      There is a whole field of study devoted to this subject...check up on Numerical Analysis

    11. 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!
    12. Re:Seems dumb to me by ChadN · · Score: 1

      Forgive the reply to myself, but just to clarify: Yes, if you have 0.5 then you probably don't need to round it further. 0.5 is a convenience value to illustrate the concept of rounding. But what if, after some floating point operation, the "5" is just beyond the last digit of what can be stored in a floating point value? Now you DO have round it. After all operations are done, then you may round further, in order to display or store a number with less precision for convenience.

      There ARE systems that can do math directly with rational numbers, with arbitrary precision, thus reducing the need for some of the per operation rounding (or at least further reducing the impact of that rounding), but that is not the kind of quick arithmetic that typical 32 or 64 bits-per-value CPUs provide. For speed, you accept the need to round, and try to understand the consequences to your application.

      --
      "It's overkill, of course. But you can never have too much overkill." - Anonymous Slashdot Coward
    13. Re:Seems dumb to me by Anonymous Coward · · Score: 0

      Although it should be said that round off error is just one small part of numerical analysis...

    14. Re:Seems dumb to me by Tim+Browse · · Score: 2, Funny

      And thus began the slide of Vegas casinos into insolvency.

    15. Re:Seems dumb to me by Tim+Browse · · Score: 1
      There ARE systems that can do math directly with rational numbers, with arbitrary precision

      Windows Calculator, for example.

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

    17. Re:Seems dumb to me by Jackmn · · Score: 1
      Subspace! [subspacehq.com]


      You may want to update your link. SubspaceHQ hasn't worked in ages.
    18. Re:Seems dumb to me by ymgve · · Score: 1

      If your bounding box is growing, there's something wrong with the design of your code, not the rounding algorithm used.

    19. Re:Seems dumb to me by fatphil · · Score: 1

      You're confusing "with arbitrary results" with "with arbitrary precision".

      --
      Also FatPhil on SoylentNews, id 863
    20. Re:Seems dumb to me by buckthorn · · Score: 1

      The local Dave & Busters and Jillian's, both of which are entertainment establishments with video games, pool, etc.. and I think likely most other places that use tickets as a reward system will weigh them now instead of counting them. Good strategy, although I thought one day what the impact would be if you took all your tickets home and put scotch tape all over them. But then I realized that such a scheme works out to a pretty bad per-hour rate. But there's got to be an easier way to do it....

    21. Re:Seems dumb to me by Tim+Browse · · Score: 1
    22. Re:Seems dumb to me by Peeteriz · · Score: 1

      For example, calculating interest from 10,000,000 accounts. You have 10,000,000 numbers that need rounding, you want the total rounding error to be as small as possible, but you can't round after accumulation, since you need to have the 10,000,000 separate values rounded as well.

      Or, calculating daily interest accrual on account - you have 30 days in a month, so 30 numbers that need rounding, and at the end of the month you would post the rounding correction. (Difference between the 'add all and round' and 'round all and add' values). Naturally, you need a method that minimises this correction - and financial rounding methods are mandated by law probably everywhere, from USA to Nigeria.

    23. Re:Seems dumb to me by Peeteriz · · Score: 1

      Well, if your bounding box is growing, then it's not the fault of the rounding method, but of the calculations that allow the error to grow and accumulate over time.

        As soon as you stard dealing with non-discrete values (like the dimensions of your bounding box), you need to use different methods - for example, always re-calculating from the previous state is a big no-no, even if you are simply adding (the rotation trigonometry will give the horrible results you mentioned).
      You need to re-calculate the bounding box every time using the original values - the original positions of the points, rotated/moved to match the position of the object. NOT the previous position re-rotated/re-moved. If properly done, it should work at the same speed anyway, it's not computationally more expensive.

    24. Re:Seems dumb to me by fatphil · · Score: 1

      """
      If it were fixed-precision, then the 3's would eventually stop coming.)

      Thirty-two positions of precision for inexact results not good enough? The Power Calculator PowerToy uses the same arithmetic engine as Calc and lets you crank the precision to an unimaginable 512 digits.
      """

      So it _is_ fixed precision. What bleedin' idiot wrote that article?

      And 512 is pretty crap; but then again, I contribute to the Pari/GP project,
      and as a user thereof I regularly deal with numbers that require nearly
      400000 digits of precision, often more.

      --
      Also FatPhil on SoylentNews, id 863
    25. Re:Seems dumb to me by Tim+Browse · · Score: 1
      What bleedin' idiot wrote that article?

      Raymond Chen may be many things, but not a bleedin' idiot.

      To counter, I would ask, which bleedin' idiot read that article? You obviously missed:

      Today, Calc's internal computations are done with infinite precision for basic operations (addition, subtraction, multiplication, division) and 32 digits of precision for advanced operations (square root, transcendental operators).

      I trust it is clear now.

      And 512 is pretty crap

      How true. I'm guessing the vast majority of people demand more than 512 bits of precision for transcendental operators from their desktop calculator. Stands to reason.

    26. Re:Seems dumb to me by uctpjac · · Score: 1

      When you're rounding in silicon, the same considerations can apply as pen & paper: carrying too much precision costs you gates, power consumption and even clock speed.

      One of the methods not mentioned in the article and widely used in hardware - for example in GPUs - is rounding partial product arrays in multipliers. You can be sure that your favourite high performance gaming box would be more expensive and hotter without this odd rounding technique.

      The idea is that you're doing binary long multiplication; you form the partial products (the rows of numbers you'll need to add), but you exclude the least significant N columns. This is clearly an underestimate of the real multiplication result. One trick for getting pretty close to the real result is to "promote" the most significant excluded column to the least significant included column. at first surprising, this actually produces a nicely bounded approximation.

      On a big multiplier, you can often get good enough results at 1/2 the silicon area and power.

      =======

      Plug, admission and more information: I'm at http://www.arithmatica.com/ which has design software which allows designers to quickly, efficiently and verifiably build this kind of hardware.

    27. Re:Seems dumb to me by fatphil · · Score: 1

      Actually, the precision is irrelevant to my original point - which was that windows calc was notorious for inaccuracy far greater than its limited precision could account for. I actually remember trying "12.52-12.51" when it was first announced.

      Anyway, you are right that 512 bits of is actually utterly pointless for a desktop calculator. 64 should be more than most people ever need, and only rarely would anyone not specifically working in a numeric field even encounter anything that requires 96 bits of precision. MS actually trying to do a half-hearted attempt at an arbitrary precision arithmetic package was therefore addition of a completely unnecessary feature.
      And the fact that any transcendental operation is performed to a far more limited precision means that the effort isn't even half-hearted - it's a pathetic sham. One square root, and most of your signal is noise - useless.

      They should have stuck to just long doubles, and got the answer right for those.

      --
      Also FatPhil on SoylentNews, id 863
  23. 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.

  24. 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 fishbowl · · Score: 1


      "Rounding towards the nearest neighbour is the default and ubiquitously used rounding mode. "

      And if a high proportion of the input data are at ".5", whether you round up or down, you've possibly got a big problem (I realize you know that obviously).

      I love all the posts that claim to work strictly with integer arithmetic. That's wonderful until you have to deal with a fraction of your nice integer value, then you get to reinvent the floating point wheel :-)

      I especially love decimal numbers that cannot be precisely represented in binary, although I've never been able to explain it very well. (I do understand sign/exp/mantissa binary floats.)

      --
      -fb Everything not expressly forbidden is now mandatory.
    2. 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
    3. Re:Interval arithmetic by Diomidis+Spinellis · · Score: 1
      I read my comment again, and realize you're absolutely right. I overstated the advantages of interval arithmetic. I should have phrased it as follows.
      If you can't afford to perform error analysis, using an interval arithmetic package will often provide you with a reliable indication on the confidence you can place on the results of your calculation.
      I agree that error analysis isa very deep speciality, and therefore programmers not versed in it need every help they can get to produce reliable results, without having to rely on it. The IEEE 754 standard has helped a lot in this area.
  25. to name but a few? by Anonymous Coward · · Score: 0

    that's not really inviting people to visit TFA.

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

    1. Re:IEEE Standard by The_Dougster · · Score: 1
      And the IEEE standard for rounding is Banker's Rounding

      That's what I have always used for programs that calculate a cost from some other factors; for instance labor costs are sometimes calculated by multiplying minutes by some factor. The result is often a decimal value that needs to be rounded to dollars and cents. If you use banker's rounding, and you should, then the bean counter upstairs will probably get the same result as your program does. This is a good thing.

      --
      Clickety Click ...
    2. Re:IEEE Standard by bcrowell · · Score: 1

      Just because something is an IEEE standard, that doesn't mean it's approproate in all cases. TFA discusses the relative merits of the different methods in different applications.

    3. Re:IEEE Standard by Anonymous Coward · · Score: 0

      Maybe in some parts of the US that is taught, but I was taught Even Rounding in a US school. *shrug*

    4. Re:IEEE Standard by PoopMonkey · · Score: 1
      Always rounding up, which is what US kids are taught in school, will eventually create a bias and throw the aggregates off.


      Maybe it's changed, or maybe my county was just different, but that's not what I was taught. It was if it's less than .5, round down. If it's .5 or more, round up.
    5. Re:IEEE Standard by xtieburn · · Score: 1

      Um, thats what he means, you always round .5 up. Theres no reason why .5 shouldnt be rounded down.

    6. Re:IEEE Standard by LaissezFaire · · Score: 1
      I didn't know anyone else did it this way. In the Field Artillery this is "artillery expression". When you're computing Fire Direction data (i.e. the math to tell the guns where to shoot) you artillery express to the nearest even number. This can be a decimal, depending on the precision you need. Oh, and Artillerymen are still taught how to use sliderules. They work when its to cold out for the computers to turn on.

      In gunnery class if you say you've rounded something the instructor will invariably say something like "Wooo! Round up, cowboy! In the Artillery you express the number."

    7. Re:IEEE Standard by ytm · · Score: 1

      Always rounding up, which is what US kids are taught in school, will eventually create a bias and throw the aggregates off.

      Here, in the middle of Europe, I was taught to round like this:
      3.4 -> 3
      3.50-> 3
      3.51-> 4
      3.52-> 3
      ...
      3.6 -> 4

      So, if a digit after '5' is even I round down, when it is odd I round up. It can be used the other way round, but just have to be consistent over all calculations. This way the bias is minimized.

    8. Re:IEEE Standard by dan+the+person · · Score: 1

      And did you pass your maths classes?

  27. Stifling innovation in rounding by jemenake · · Score: 1
    As he states, "...the mind soon boggles at the variety and intricacies of the rounding algorithms"
    Probably because the one that everyone would *like* to use is patented.
  28. 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.
    1. Re:Social Applications by Anonymous Coward · · Score: 0

      mod parent +5 Funny

      it's so funny; it hurts

    2. Re:Social Applications by grammar+fascist · · Score: 1

      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)


      Don't forget:

      The banker's rounders (round toward even: 0.5 is 0, 1.5 is 2)
      The politicians (it's half a glass)
      The "it's all relative" crowd (the glass is too big)

      --
      I got my Linux laptop at System76.
    3. Re:Social Applications by reg · · Score: 1

      And, of course, engineering rounding... 0.5 = 1.0 or 0.0, with some factor of safety. Works particularly well if the glass contains beer. Which direction one needs the factor of safety depends on who's buying... But at least it means you're 0.5 of the way to the next round.

      Regards,
      -Jeremy

  29. the best rounding algorithm by circletimessquare · · Score: 0, Offtopic

    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

    rip dude

    --
    intellectual property law is philosophically incoherent. it is your moral duty to ignore it or sabotage it
    1. Re:the best rounding algorithm by psykocrime · · Score: 1

      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
  30. Rounding Algorithms are... by __aaclcg7560 · · Score: 1

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

    1. Re:Rounding Algorithms are... by Sparr0 · · Score: 1

      You will never forget the day you find your first bug in gcc. I never did :)

    2. Re:Rounding Algorithms are... by 1729 · · Score: 1
      You will never forget the day you find your first bug in gcc. I never did :)

      I don't remember the day I first found a bug in gcc. I have only a vague recollection of the first bug I introduced into gcc . . . :)

  31. In-Story Dupe? by Boronx · · Score: 1

    What's the difference between round-toward-zero and truncate is? Or floor round and round down? Or ceiling round and round up?

    1. Re:In-Story Dupe? by Anonymous Coward · · Score: 0

      Rounding a negative number towards zero is "rounding up", whereas rounding a positive number towards zero is "rounding down"

    2. Re:In-Story Dupe? by Anonymous Coward · · Score: 0

      negative numbers!

    3. Re:In-Story Dupe? by Boronx · · Score: 1

      But if I truncate a negative number, I round up. If I truncate a positive number, I round down. Round towards zero.

      If I floor a number, always rounding down. If I ceiling the number, always rounding up, positive or negative.

      trunc(-1.5) = -1 = round2zero(-1.5)
      trunc(1.5) = 1 = round2zero(1.5)

      floor(-1.5) = -2 = rounddown(-1.5)
      floor(1.5) = 1 = rounddown(1.5)

      ceiling(-1.5) = -1 = roundup(-1.5)
      ceiling(1.5) = 2 = roundup(1.5)

  32. so, what's the diffrence by autopr0n · · Score: 1

    between round to zero and floor, and round to infinity and ceiling?

    --
    autopr0n is like, down and stuff.
    1. Re:so, what's the diffrence by Ekarderif · · Score: 1

      Round to zero goes towards zero: 2.5 to 2; -2.5 to 22 Floor goes towards -infinity: 2.5 to 2; -2.5 to 23 Round to infinity goes towards +/- infinity: 2.5 to 3; -2.5 to -3 Ceiling goes towards +infinity: 2.5 to 3; -2.5 to -2

  33. Fix() in VB by YodaToo · · Score: 1

    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

    1. Re:Fix() in VB by rodac · · Score: 1

      There are some very good books that explains this and how one should do calculations on computers and how to estimate the error propagation and growth. The field that covers this is called Numerical Analysis and should be part of any math or comp sci training. A good introduction textbook for this is Numerical Methods by Germunds Dahlquist http://www.amazon.com/gp/product/0486428079/qid=11 36506488/sr=8-5/ref=pd_bbs_5/104-6440517-4726329?n =507846&s=books&v=glance

    2. Re:Fix() in VB by YodaToo · · Score: 1

      I've actually studied Numerical Analysis which is why I caught this and wasn't terribly surprised by it, but there is a tendancy when whipping up a quick bit of code to not think about nor look for such things.

    3. Re:Fix() in VB by Anonymous Coward · · Score: 0

      Maybe Fix() is broken?

      Or it has probably been written on the first Pentium.

  34. The canonical reference... by Doctor+Memory · · Score: 1

    ...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...
    1. Re:The canonical reference... by Atzanteol · · Score: 1

      Floats and doubles... Water tennis...

      *grin*

      <fry>I get it!</fry>

      --
      "Ignorance more frequently begets confidence than does knowledge"

      - Charles Darwin
  35. 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
  36. What good will that do you... by dotgain · · Score: 1

    ...in federal pound-me-in-the-ass prison.

  37. that's rounding up by goombah99 · · Score: 1

    your algorithm always rounts 0.5 up.

    --
    Some drink at the fountain of knowledge. Others just gargle.
    1. Re:that's rounding up by amjacobs · · Score: 1

      No, it's rounding to the nearest integer. If the fractional value of the number is 0.5 or greater, the number will be rounded up. If the fractional value is less than 0.5 the number is rounded down.

      For example, take the number 2.3:

      2.3 + 0.5 = 2.8 --> 2

      While the number 2.8 gives the following result:

      2.8 + 0.5 = 3.3 --> 3

      In order to extend this method to arbitrary precision, add 5*10^-n to the original number before truncation. (where n controls the rounding precision)

    2. Re:that's rounding up by goombah99 · · Score: 1

      Hey, You want to be my bank? I'm going to keep depoiting 0.5 cents and withdrawing pennies. How you treat 0.5 matters. You are rounding up.

      --
      Some drink at the fountain of knowledge. Others just gargle.
    3. Re:that's rounding up by idonthack · · Score: 1
      No, it's rounding to the nearest integer.
      It only works properly for positive numbers, though.

      -1.3 + 0.5 = -0.8 truncates to 0, and I'm pretty sure that's not what you want. He should test to see which side of 0 the number is on, and then add or subtract depending on positive or negative.

      I'm assuming he wants standard rounding, going to the next integer (up for positive, down for negative) if it's on the 0.5 mark.
      --
      Why is it that when you believe something it's an opinion, but when I believe something it's a manifesto?
    4. 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!)

    5. Re:that's rounding up by Anonymous Coward · · Score: 0

      Hey,

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

      I don't quite understand that (may be due to my limited experience of banking). Any chance you could explain?

      Thank you.

    6. Re:that's rounding up by Sarisar · · Score: 1

      OK, for those who can't or won't work this out - assume you have 100 bucks in your account, and the interest rate is 100% (yeah I wish, but it makes the maths easier!)

      If you leave your money in all year, you have 200 bucks (100 * 100%)

      If you take your money out after 1/2 a year, you would get 150 bucks (100 bucks * 50%). Put it back in and then take it out at the end of the year and you get 225 bucks (150 * 50%).

      If you do it every 1/4 year you would get 100 * 25% = 125 in the first quarter, then 125 * 25% = 156.25 in the second quarter, 156.25 * 25% = 195.3125 for the third and then 195.3125 * 25% = 244.10625 for the full year. (OK they would round down but I didn't here). You have made 44 bucks by just visiting your bank a few times!

      The more you go in and take your money out and put it back in, the more you gain over the entire year if they calculated interest on what you had in exactly up to that date.

    7. Re:that's rounding up by Anonymous Coward · · Score: 0

      Thanks =)

    8. Re:that's rounding up by Sarisar · · Score: 1

      You're welcome lol

    9. Re:that's rounding up by Anonymous Coward · · Score: 0

      He's not rounding up. 5.1 rounded up is 6.0. He is rounding-to-nearest-up in my lingo, rounding-half-up in the lingo of TFA. Rounding up is a completely different kettle of fish.

    10. Re:that's rounding up by Anonymous Coward · · Score: 0

      Your math teacher is a moron. No, an UTTER moron. A normal person is entitled not to know this. To not know this, as a math teacher, and then to teach the wrong thing, is fucking appalling.

      If an account pays 100% per year it pays 41.421% per six months. Not 50%. It's not 100 / 2 its the 2nd root of 200%, minus 100%. It is calculated precisely so that your little scam doesn't work! Work it through:

      $100 * 1.41421 = $141.421
      $141.421 * 1.41421 = $200.00

      If this wasn't the case you'd be earning more interest over the first six months than you were over the second, and that's just not how interest works.

      Banks accrue interest daily overnight based on what you leave in the bank overnight. This would be the 365th, 366th or 365.25th root of 200%, minus 100%, per day. That would be about 0.19% per day, rather than the 0.27% you might naively expect.

    11. Re:that's rounding up by hawkfish · · Score: 1

      Please don't call people morons when you don't know what you are talking about.

      All you have done is reduce the payment period from 1 year to 1 day. Go look up "continuous compound interest" to see the limiting case.

      You are right that banks have policies to prevent this sort of scam, but they are NOT what you describe. Rather, this is what the "penalties for early withdrawal" clause famed in so many off-colour jokes is all about.

      --
      You will not drink with us, but you would taste our steel? - Walter Matthau, The Pirates
  38. 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)

    1. Re:Doesn't work for negative numbers. by RackinFrackin · · Score: 1

      That's a good point. I use this in spreadsheets to average grades, so all the numbers I deal with are nonnegative. I've never considered how this function would work for negative numbers.

    2. Re:Doesn't work for negative numbers. by Anonymous Coward · · Score: 0

      Since when are logic statements a problem?
      Let x equal the number you're rounding
      if (x 0)
      return trunc(x-0.5)
      else
      return trunc(x+0.5)
      (Sorry for the pseudocode. I forgot what the truncation function in C is, so I kind of just faked everything)
      You can even omit the else if you want. (Less clean code though, IMO)
      3-4 lines wrapped in a function or method, or if you're really crazy, you can probably get it in very few lines of ASM (I *doubt* less than 3 though) Seriously, not tough. It's not one line of code (although, now that I think of it, if you are into PERL and obfuscated lines, then you can get the first if statement on one line, and then the return on the next line.... soo.... 2. Even less tough.)

      2-4 lines.

    3. Re:Doesn't work for negative numbers. by Matt+Edd · · Score: 1

      I wonder why you worry about efficiency when dealing with a spreadsheet?

    4. Re:Doesn't work for negative numbers. by Karma+Farmer · · Score: 1

      Since when don't spreadsheets have every one of these algorithms already built in?

    5. Re:Doesn't work for negative numbers. by CarpetShark · · Score: 1
      I use this in spreadsheets to average grades, so all the numbers I deal with are nonnegative.
      You must have the smarter students ;)
  39. 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.

  40. 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!
  41. I like how C# float and double variables are... by Wisgary · · Score: 0

    ...useless. This may be a bit off topic but I was trying out C# the other day and just about all my doubles and/or floats got screwed up. And it wasn't even division or multiplication! It was simple addition and subtraction. I would enter maybe 1 and .6, subtract them, and instead of .4 I'd get... .3999999393993489348938428975932498 or .40000000000000000000000000000000000001

    Had to use the decimal datatype for anything wortwhile, meh. Anyone know why my floats and doubles were rendered useless?

    1. Re:I like how C# float and double variables are... by rodac · · Score: 1

      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.

    2. Re:I like how C# float and double variables are... by Wisgary · · Score: 0

      I'm actually taking numerical analysis next semester. But I do know how they do it from my computer architecture classes. I'm just curious as to why other languages (for example C++) floats and doubles don't give me the same problem as C# with simple addition.

    3. Re:I like how C# float and double variables are... by rodac · · Score: 1

      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.

    4. Re:I like how C# float and double variables are... by Wisgary · · Score: 0

      Wow, that's an awful lot of work, shouldn't the compiler be doing this stuff under the hood for me? I guess I'll learn about this come next semester.

    5. Re:I like how C# float and double variables are... by rodac · · Score: 1

      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.

    6. Re:I like how C# float and double variables are... by Wisgary · · Score: 0

      Yeah I see what you mean, fiddled around with the code, just about everything gives me wrong amounts. float a = 0.0; float b = 1.0; for ( int i = 5000000; i > 0; i--) { a += 0.0000001f; b -= 0.0000001f; } printf("a:%f\n",a); printf("b:%f\n",b); That outputs a:0.476541 b:0.427965 That sucks, guess I have a lot of learning to do, thanks for the help, I might just get that book as well as my regular college textbooks, thanks.

    7. Re:I like how C# float and double variables are... by metamatic · · Score: 1

      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
  42. round-to-the-nearest-multiple-of-pi by Anonymous Coward · · Score: 0

    Enough said!

  43. floor() is slow by Anonymous Coward · · Score: 1, Informative

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

    typedef union masker
    {
            double d;
            int64_t n;
    } masker_t;

    int round( double x )
    {
            static const int64_t mask = 1LL 63; // IEEE sign bit is first
            masker_t half;
            half.d = 0.5;
            masker_t a;
            a.d = x;
            half.n |= ( a.n & mask ); // set sign bit for half
            x += half.d; // add .5 to positive x, subtract .5 from negative x
            return( ( int ) x ); // truncate and return
    }

  44. Round Random? Why? by robgamble · · Score: 1

    Why would you even bother rounding if you didn't know whether the result was going up or down?

    --
    No sig for you!
  45. 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 bill_mcgonigle · · Score: 1

      I would say that $3.00 is just as precise as $3.21. If you want less precision, you have to go to $3...

      Me too, but I always got those marked wrong in Science class - purposely because nobody could explain to me why 3.00 was less precise than 3.21, but according to the textbooks it is. I don't get it.

      --
      My God, it's Full of Source!
      OUTSIDE_IP=$(dig +short my.ip @outsideip.net)
    2. Re:Precision by Anonymous Coward · · Score: 0

      Hmm, I'm pretty sure my textbooks said trailing zeros are significant, leading zeros not.

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

  46. All I ever needed to know about rounding, I... by psykocrime · · Score: 1

    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
  47. 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?
  48. He missed some by Nightlight3 · · Score: 2, Interesting

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

  49. Ninjas! by idonthack · · Score: 1

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

    1. Re:Old school by Anonymous Coward · · Score: 0

      Ah, so that's why... when I dial 068768728 I always end up at Pizza Hut!

  51. 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 wildsurf · · Score: 1

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

      This is incorrect.

      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.

      --
      Weeks of coding saves hours of planning.
    3. 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

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

    5. 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.
    6. Re:Only with money in fractions by Anonymous Coward · · Score: 0

      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.

      Huh, where did this come from??

      Who cares what notation you use for negative numbers, as long as it is defined and used consistently?

      Are you saying that folks who use parens for negatives are getting wrong answers??

    7. Re:Only with money in fractions by sylvester · · Score: 1

      Err..Under banker's rounding, only "exact" halves are rounded to the even. 4.56 would go to 5, always.

      Your "review" of what we do when we round is bollocks.

      -Rob

    8. 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
    9. Re:Only with money in fractions by MarkusQ · · Score: 1
      Please read the next-to-the-last paragraph of the post to which you were responding. And it might help if you pause to think a little before saying that something is "bollocks".

      --MarkusQ

    10. Re:Only with money in fractions by fatphil · · Score: 1

      "I know whereof I speak, " ...
      "the number 4.56106531 would be rounded to 4 in the "nearest even" case"

      You are nothing but a long-winded bullshitter, spouting crap.
      Your up-moderations are utterly undeserved.

      But then again, those I know familiar with NA always call it "nearest or even",
      whoever decided to elide such an important word from the name should be shot.

      One extra syllable and the world would have been spared your misinformation.

      --
      Also FatPhil on SoylentNews, id 863
    11. Re:Only with money in fractions by MarkusQ · · Score: 1

      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:
      When floating-point operations are done with a guard digit, they are not as accurate as if they were computed exactly then rounded to the nearest floating-point number.
      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...
      For what it is worth, I agree with your points (and, of course, with Knuth) when it comes to things like dealing with the about-to-be-dropped bits in FP hardware--the case of a single binary guard bit, computed as he describes, is isomorphic with that of money; the data sample is strongly biased towards exact halves (the guard bit=1) and, since this rounding is only/always being done on the least significant bit of a floating point value, we are more concerned with fairness (see the example that he cites) than with accuracy (e.g., the second quote) which can be dealt with (bounded) by other means.

      -- MarkusQ

    12. 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
    13. Re:Only with money in fractions by daran0815 · · Score: 1

      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.
      This really depends on where you get your numbers from:-)

      Consider numbers actually consisting of three parts. The integral part to where you wana round, the known fractional part that you base your rounding on and a third part of following unknown digits. The last part is usually consisting of all zeroes for monetary values. So your number is:

      xxx.yyzzz....

      So in your example 1.0 is actually 1.0zzz with z representing unknown digits. Which means that rounding 1.0 to 1 is NOT exact when talking about natural numbers. Same goes for 1.5zzz, where rounding up may be more precise if those z are nonzero.

      Bankers rounding is cute and nice for quite a few applications, but it *can* also introduce a bias of its own, depending on what you do. I hope you see now, why MarkusQ has a point.

      Greetz,
      Daran

    14. Re:Only with money in fractions by mesterha · · Score: 1

      This really depends on where you get your numbers from:-)

      Of course, I was giving a rough justification. I encourage people to read the references I gave for more details. But you do have a point, making additional assumptions about where the numbers come from and what operations you are going to perform can often be used to greatly reduce round-off error. However, in general, if you are doing floating point rounding with numbers that are already rounded then round to even is preferred.

      Consider numbers actually consisting of three parts. The integral part to where you wana round, the known fractional part that you base your rounding on and a third part of following unknown digits. The last part is usually consisting of all zeroes for monetary values. So your number is:

      xxx.yyzzz....

      So in your example 1.0 is actually 1.0zzz with z representing unknown digits. Which means that rounding 1.0 to 1 is NOT exact when talking about natural numbers. Same goes for 1.5zzz, where rounding up may be more precise if those z are nonzero.

      As I already said, this means the numbers as given have been truncated. However, as you do further calculation with these numbers they will be rounded and therefore, rounding to even is preferred. Ideally you want to start with rounded numbers since the initial truncation will cause a lot of bias, but sometimes you can't control that.

      Bankers rounding is cute and nice for quite a few applications, but it *can* also introduce a bias of its own, depending on what you do. I hope you see now, why MarkusQ has a point.

      I don't mean to knock MarkusQ, but he was giving bad information and based on his moderation points people were believing him. I had moderation points, but I figured it would be more informative to explain why he was wrong. My hat is off to him. It's much easier to explain a true fact than to convince people of a mistaken belief. (Or at least I hope so.)

      --

      Chris Mesterharm
  52. 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.

  53. At least by wildsurf · · Score: 1

    At least this Slashdot poster appears to be well-rounded.

    --
    Weeks of coding saves hours of planning.
  54. Not as fast as it could be by Anonymous Coward · · Score: 0

    When inlined, that if-statement will prevent efficient loop pipelining. If you're processing a lot of floating-point numbers and performance matters, that won't be very fast.

    And the way to truncate floating point numbers in C is to assign them to a integer type.

    1. Re:Not as fast as it could be by Anonymous Coward · · Score: 0

      Using an if or not is kind of a moot point since converting a float to int will stall the pipeline too (although I think there's an SSE function that does the conversion without stalling), of course just because you are performing rounding doesn't mean you are converting to an int. The return value of std::floor(float) is a float, so there is not necessarily a pipeline stall. /AC who wrote great-grandparent post

  55. Yup by Anonymous Coward · · Score: 0

    That's one of the many things about Visual Basic that I always hated. Instead of doing what you expected it to do when casting a floating point number to an integer, the @#$& thing would round up, forcing you to wander through practically worthless help screens to find a simple way to undo what it did. Rounding should be bloody well left to the programmer. If you don't know how to round something, you have no hope getting a simple program to work.

  56. Re:Round Random? Why? by cnettel · · Score: 1

    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.

  57. 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"
  58. Re:Canadian, eh? by TedTschopp · · Score: 1

    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
  59. all depends... by misanthrope101 · · Score: 1
    Why would my wife being pregnant be a problem?
    Depends on where you were on the night in question. I work in a military hospital. Military people often go TDY (temporary duty) somewhere else, often for months on end. I see guys back from TDY or deployement all the time, in the office with their pregnant wives for a check-up.

    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.

    1. Re:all depends... by Bork · · Score: 1

      I knew a few friends in the military that wished they were around when there kid was conceived. Did not feel to sorry for them though, a few kids were conceived while they were around and the husbands of those wifes were someplace else.

    2. Re:all depends... by Mr+Z · · Score: 1

      Is it that hard to add/subtract 3 months and a handful of days? Ignoring that the standardized gestational period is about 266 days, it seems like 3 months "give or take a week" should be easy for just about anyone. (Hint: If given the due date, add 3 months and 9 days to get approx. date of conception on the previous year. If given the conception date, subtract 3 months and 9 days to get approx. date of birth on the following year.) This isn't multiplication or exponentiation. (Ok, it's a different sort of multiplication... but that's a different story.)

      Chances are, in a situation like this, "give or take a month" is all the precision you need.

  60. Rounding? by students · · Score: 2, Funny

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

  61. Anecdote time... by protocoldroid · · Score: 1, Interesting

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

  62. I wrote it... by Anonymous Coward · · Score: 0

    I had to write an algorithm similar to this soon after I was hired at my current position. The reason the algorithm was needed was because when a dollar is split to pay part of three different charges, you have to give one charge the extra penny. Now imagine there are 21 charges, where some have higher priority than others, and they are all for random amounts, but if the person pays half, they want each bill to be paid off halfway.

    Well, sometimes the rounding wasn't working out, one $10 charge would get paid $4.99, another $5.01, instead of each getting exactly $5. So I had to write something that would keep track of which accounts needed an extra penny to get to the even amount, and which had extra pennies to give. Then there was the "give-a-penny-take-a-penny" function that looked through them all and transferred money around to the account that needed it.

    And yes, we've talked among ourselves to figure out if there's a way to steal small amounts of money as all this happens. The problem is we write reports that show where all the money went, and into which accounts, and we're all too lazy to change every report to ignore the special account where the money would go. Then there's the fact that we have to change the code every so often to deal with some new requirement, or improve performance, or something, so someone would certainly find it eventually. Then that means they have to be let in on the deal, and get a piece of the money.

  63. Re:IEEE Standard (Convergent Rounding is best) by Anonymous Coward · · Score: 0

    Convergent rounding is used extensively in DSPs (its the best). Now it looks like the new term is Round-half-even.

  64. Whoops, preview button by Wisgary · · Score: 0

    Whoops, I forgot to hit the preview button.

            float a = 0;
            float b = 1;

            for ( int i = 5000000; i > 0; i--)
            {
                    a += 0.0000001;
                    b -= 0.0000001;
            }

            printf("a:%f\n",a);
            printf("b:%f\n",b);

    outputs:

    a:0.476541
    b:0.427965

    Both should output .5 :(

  65. Danger Will Robinson! by Anne+Thwacks · · Score: 1

    Right after they have been all listed, the USPTO will grant SCO patents on all of them!

    --
    Sent from my ASR33 using ASCII
  66. Lorenz attractor by pfafrich · · Score: 1

    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.
  67. 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.
    1. Re:I never thought I knew what was happening... by omeg · · Score: 1

      a = 0.001;
      b = 0;
      for (i=0; i<1000; i++) {
              b += a;
      }
      trace(b); // traces 1!

    2. Re:I never thought I knew what was happening... by matfud · · Score: 1

      How about the ever excellent "never terminating loop"

      float i = 0.0;

      for (float i = 0.0; i < 10000000; i+=1.0) {
      //  do stuff here
      }

  68. Or Enron by Sigg3.net · · Score: 0

    Or Enron.
    Round significantly up and harvest percentages.

  69. 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”
  70. 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...)

  71. Used in Visual Basic by Nurgled · · Score: 1

    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.

  72. Re:Pizza Hut by Anonymous Coward · · Score: 0

    I don't get it.

  73. Square not Round by xzanthar · · Score: 1

    Isn't that Square, not Round?

    --
    I encrypt all my files with Double XOR Encryption!
  74. rounding in .NET by Anonymous Coward · · Score: 0

    So yeah, use the rounding functions in .NET and you get bankers rounding.
    Want to not use bankers rounding? Easy! convert it to a string first.
    wait a minute, that can't be efficient, can it?
    Any one know of an alternative?

  75. NOT to be construed as tax advice by renehollan · · Score: 1

    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.
  76. Well, that's odd. by osric · · Score: 1

    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.
  77. I hate such dithering by RedLaggedTeut · · Score: 1

    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.
    1. Re:I hate such dithering by Mr+Z · · Score: 1

      Actually, some programs implement various forms of stochastic dithering (random rounding) for that reason. What those algorithms do is add a random or pseudo-random number to each value to cause fractional values to quantize either to the next larger or next smaller number with a probability related to the fractional value.

      How does that help? The end result is slightly noisier than the Floyd-Steinberg case, but you stand the opportunity to make things look better in mouse-overs and animations. Specifically, if you use pseudo-random numbers for the random component, and you use the same pseudo-random number for a given pixel position, then you have "stable noise," avoiding the inherent sparkling that you'd otherwise get over the course of an image due to algorithms like Floyd Steinberg. You also avoid the cross-hatch pattern that fixed dither patterns like "ordered dither" give you.

      Ordered dither and stochastic dither are actually nearly equivalent for the most part. Both add a "rounding pattern" to the image before quantizing, with ordered dither adding a fixed pattern and stochastic dither adding a random or pseudo-random pattern. This PDF file seems to give a good, brief overview of various quantization techniques for images.

      You probably hate Floyd-Steinberg for web development--it screws up mouse-overs and bloats GIFs--but what you probably don't realize is that all those "1-bit DAC" CD players with "BIGNUMx oversampling" out there are using delta-sigma modulation, which is the same concept of error-diffusion, but for a 1 dimensional signal.

      --Joe

    2. Re:I hate such dithering by Mr+Z · · Score: 1

      Erf... I dropped a phrase from one sentence. Here's a minor edit: "...and you use the same pseudo-random number for a given pixel position across all images in a sequence..."

      --Joe

  78. Modded as troll? LOL by RedLaggedTeut · · Score: 1

    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.