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
?
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With