Ask Your Question

modulo of a non-integer

asked 2011-02-11 16:10:42 +0200

mhfrey gravatar image

updated 2011-02-11 18:25:33 +0200

Does Sage support modulo of a non-integer? for example:

var("m b")

This returns 3.5*pi instead of the expected 1.5*pi or


for which I expect 1.1.

I can calculate it explicitly with b-m*int(b/m), but I cannot find the mod version in sage. Which seems surprising.

edit retag flag offensive close merge delete

2 Answers

Sort by » oldest newest most voted

answered 2011-02-12 09:46:01 +0200

DSM gravatar image

updated 2011-02-12 09:46:51 +0200

If you only care about numerical values, you can use %:

sage: float(7.7) % float(2.2)
sage: 7.7 % 2.2

but these won't work for symbolic expressions, unless you play subclassing games:

class ModExp(Expression):
    def __init__(self, value):
        Expression.__init__(self, SR, value)
    def __mod__(self, other):
        return self-floor(self/other)*other
    def mod(self, other):
        return self.__mod__(other)

sage: pi = ModExp(pi)
sage: pi % (pi*3/4)
sage: pi.mod(pi*3/4)
edit flag offensive delete link more


well, this is a *much* better answer :)

niles gravatar imageniles ( 2011-02-12 10:00:49 +0200 )edit

answered 2011-02-12 09:03:09 +0200

niles gravatar image

I think there is no such function in Sage right now. I did see that the Octave rem() function works for non-integers as you are expecting. There is an interface for Octave in Sage, but note that it requires installing Octave separately:

The commands in this section only work if you have the optional “octave” interpreter installed and available in your PATH. It’s not necessary to install any special Sage packages.

I've also seen some indication that the JavaScript modulus operator works this way for non-integers too, but I can't find a good reference for it.

If you really want this feature to be added to sage, you should ask about it on the sage-devel list, and file a Trac ticket for it. Then you should write a patch to do what you want!

edit flag offensive delete link more

Your Answer

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

Add Answer

Question Tools


Asked: 2011-02-11 16:10:42 +0200

Seen: 2,688 times

Last updated: Feb 12 '11