Ask Your Question
1

modulo of a non-integer

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

mhfrey gravatar image

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

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

var("m b")
m=2*pi, 
b=3.5*pi, 
b.mod(m),

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

M=2.2,
B=7.7,
B.mod(M)

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
1

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

DSM gravatar image

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

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

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

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)
1/4*pi
sage: pi.mod(pi*3/4)
1/4*pi
edit flag offensive delete link more

Comments

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

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

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

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

Stats

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

Seen: 2,778 times

Last updated: Feb 12 '11