Modulo operator on reals: e.g., 4.9 % 10 = 4.9 but 5.1 % 10 = -4.9 instead of 5.1. Why??

19 views
Skip to first unread message

Privasie Invazhian

unread,
Apr 10, 2014, 11:23:06 PM4/10/14
to sage-s...@googlegroups.com
I'm running Sage 5.3 on a MacBook Pro with OS X version 10.7.5, and I don't understand why the modulo operator % works so differently on reals and on integers or how I can work around it.

For instance,   4 % 10 = 4  and 6 % 10 = 10, just as I would expect.

But while 4.9 % 10 = 4.9 as expected, 5.1 % 10 = -4.9 instead of 5.1.  

And as far as I can tell, for any positive integer or real modulus n and any positive integer m and positive noninteger x < n, 

(mn + x) % n = x  if x < n/2,

but 

(mn + x) % n = x-n if x > n/2.

I don't understand this AT ALL.

(Apologies if it's a simple question that I'm failing to understand because I'm a relative novice: I would go to the ask-sage-math forum as recommended but the posting feature there seems to be currently disabled for low-karma posters.)

Thanks for any enlightenment,
Kim

Nils Bruin

unread,
Apr 10, 2014, 11:40:53 PM4/10/14
to sage-s...@googlegroups.com

 sage: 5.1 % 10
-4.90000000000000
sage: a=5.1
sage: a.__mod__?    #unfortunately, you have to know that "%" eventually calls "__mod__", but that's just python
Type:       method-wrapper
String Form:<method-wrapper '__mod__' of sage.rings.real_mpfr.RealLiteral object at 0x70986e0>
Definition: a.__mod__(left, right)
Docstring:
   Return the value of "left - n*right", rounded according to the
   rounding mode of the parent, where "n" is the integer quotient of
   "x" divided by "y". The integer "n" is rounded toward the nearest
   integer (ties rounded to even).

   EXAMPLES:

      sage: 10.0 % 2r
      0.000000000000000
      sage: 20r % .5
      0.000000000000000

      sage 1.1 % 0.25
      0.100000000000000

This is just how "%" is implement in MPFR (the main floating point library in sage)

Privasie Invazhian

unread,
Apr 11, 2014, 12:44:58 AM4/11/14
to sage-s...@googlegroups.com
Thanks!  I ended up kluging it into an "ordinary" modulo operator by making a function to check the sign of the result and return x if the result is positive and n+x if the result is negative, which makes it look like the sort of "modulo n" function I'm used to.  

Thanks again for your help,
Kim
Reply all
Reply to author
Forward
0 new messages