Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to do integer division in sympy?

I have a very long expression that I think can be simplified, and I thought sympy would be the perfect way to do it. Unfortunately the formula relies on a couple of integer divides, and I can't find any way to represent those in sympy.

>>> x=Symbol('x')
>>> (x+1)/2
x/2 + 1/2

Clearly not what I want, 1/2 isn't an integer.

>>> (x+1)//2
TypeError: unsupported operand type(s) for //: 'Add' and 'int'

Obviously sympy doesn't handle //.

>>> Integer((x+1)/2)
#   A long list of error messages, ending with ...
TypeError: Integer can only work with integer expressions.

It seems that Integer is only intended to work on constant numbers, not formulas.

There's a function trunc but it doesn't seem to do anything similar to what I want.

Is there any way to represent an integer division in sympy?

like image 938
Mark Ransom Avatar asked May 05 '17 04:05

Mark Ransom


1 Answers

Criteria

I assume that you want a function div that passes the following tests:

from sympy import sympify, simplify, Symbol

def test_div(div):
    # check that div behaves as intended for integers
    for i in range(-5,5):
        for j in range(-5,5):
            if j==0: continue
            assert i//j == div(sympify(i),sympify(j))

    # check that div’s output can be simplified
    x = Symbol("x", integer=True)
    assert simplify( div(x+1,2) - div(x-1,2) ) == 1

Modulo

You can realise an integer division using the modulo operator as follows:

div = lambda x,y: (x-x%y)/y

As SymPy supports modulo arithmetics and is capable of simplifying it, this function passes the above tests. However, if no full simplification is possible, you will end up with modulo expressions that may be undesired.

Floor

As already mentioned in the comments, SymPy provides a floor function, which could be used to acquire an integer division as (which is also how the // operator for expressions is implemented):

div = lambda x,y: sympy.floor(x/y)

However, floor does not support simplifications and therefore fails the second test.

like image 176
Wrzlprmft Avatar answered Oct 15 '22 04:10

Wrzlprmft