Ask Your Question

Why (11+2/3)%2=1 and (11+1/3)%2=0?

asked 2015-12-21 15:43:37 -0600

roland gravatar image

updated 2015-12-21 17:23:43 -0600

I did not expect this behavior... For instance, I would expect an error message or a warning.

Is there an explanation?

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-12-21 17:20:53 -0600

updated 2015-12-21 17:34:25 -0600

Each Sage object might behave differently with respect to the modulo operator %. In your situation this is due to the implementation of this operator for rational numbers. Namely x % y if x is rational and y integer Sage will do the following

def modulo_for_rational(x,y):
    x = ZZ(x)
    n = x.numerator() % y
    d = x.denominator() % y
    d = d.inverse_mod(y)
    return (n * d) % y

Note that all the modulo in the above code are between integers. Hence the rationale is: in x % y with x a rational and y an integer should be considered as a computation in ZZ / y ZZ.

This is indeed inconsistent with the behavior of % when x is a floating point number... where the definition is of x % y is the unique real number in [-y/2, y/2) of the form x + n y with n integer.

sage: 3.2 % 1
sage: 3.7 % 1

PS: you can look at the complete source code of the modulo operator with

sage: Rational.__mod__??
edit flag offensive delete link more


vdelecroix gravatar imagevdelecroix ( 2015-12-21 17:34:45 -0600 )edit

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account.

Add Answer

Question Tools

1 follower


Asked: 2015-12-21 15:43:37 -0600

Seen: 58 times

Last updated: Dec 21 '15