From: "Benjamin J. Tilly" Date: 2001-05-08T05:45:43+09:00 Subject: [ruby-talk:14809] RE: Integer division oddness >===== Original Message From "Mike T. Miller" ===== >My father pointed out this oddity. > >Using integer math, try this on various languages: > >-10 / 9 > >For ruby, python and tcl you get: -2! >For java, c and gforth you get: -1 > >Getting -2 seems really wrong to me. I looked at the >code for ruby and found this: (numeric.c: line 1056) > > if ((mod < 0 && y > 0) || (mod > 0 && y < 0)) { > mod += y; > div -= 1; > } > >So, bascially, one is subtracted on purpose in this case. >Is this an accepted way to do integer division tha I'm not >familiar with? It depends. If you promise that the remainder will always be in the range [0,1), it is what you have to do. If you are a speed demon you may prefer saying that the sign of the modulus is not defined and leave this out. If you intend to use the modulus it is more useful to know that it is in that range. But the vast majority of the time, people are not using the modulus. So -2 is theoretically a "better" answer. But it is slower to produce. It is therefore probably not a coincidence that of the 6 languages that you tried, the ones which are more concerned with speed all gave -1 for an answer, and the ones which are trying to be high-level languages gave -2. BTW to add a data point just to be confusing, Perl does it 3 ways. :-) 1. By default Perl gives an answer in floating point. 2. If you use integer (saying you want speed) you get -1. 3. If you use the % (ie modulus) operator by default you get 8 (reflecting the "careful" rounding) but if you have "use integer" in place you get -1 for an answer. Note with item 3 that the answer that Perl gives *changes* depending on whether you are hinting that you care about speed. Cheers, Ben