On 8/10/06, Daniel Berger <Daniel.Berger / qwest.com> wrote: > Help a guy out who got B's and C's in math classes in college: > > Ruby 1.8.4 on Solaris 10: > > irb(main):013:0> -1234567890987654321.remainder(13731) > => -6966 > irb(main):014:0> -1234567890987654321.remainder(13731.24) > => -9906.22531493148 > irb(main):015:0> -1234567890987654321.modulo(13731) > => 6765 > irb(main):016:0> -1234567890987654321.modulo(13731.24) > => 3825.01468506852 > > Basically, I'm trying to figure out the nuances of Bignum#remainder vs > Bignum#modulo. To confuse myself even further K&R (2nd ed, p. 41) says you > can't do modulus on double or long, and that the sign result is machine > dependent for negative operands. > > Can someone explain the subtleties of this to me (or point me to a link that > does)? An archive search didn't reveal anything obvious. > > Perhaps the documentation in bignum.c needs further exposition? Or should I > just *know* this? Well perhaps the c code isn't the best place to understand ruby semantics. I'd look at the class library documentation http://www.ruby-doc.org is a good online resource for that. If we look at the Numeric class (from which all the standard numeric classes descend: http://www.ruby-doc.org/core/classes/Numeric.html And poke around at the modulo and remainder method definitions, we find that remainder is defined in terms of modulo, so that dividend.remainder(divisor) is divendend.modulo(divisor) if dividend and divisor have the same sign, and dividend.mod(divisor)-divisor otherwise. And if we look at mod we find that it's implemented as if it called divmod in whose specification we find a nice table showing how modulo and remainder are related under various conditions. http://www.ruby-doc.org/core/classes/Numeric.html#M000032 As for the K&R restrictions and caveats, those have to do with C whose operations are defined on machine-dependent representations, where integers have a small fixed number of bits. Since ruby automatically converts to Bignums when integers can't be represented by Fixnums, it doesn't run into the boundary conditions on representational overflow. -- Rick DeNatale IPMS/USA Region 12 Coordinator http://ipmsr12.denhaven2.com/ Visit the Project Mercury Wiki Site http://www.mercuryspacecraft.com/