I am trying to ceil the integer x
divided by a constant:
>>> x = sympy.Symbol("x", integer=True)
>>> (x + 4 - 1) // 4
floor(x/4 + 3/4)
If we take this out of the context of sympy, the expression is incorrect when assuming integer arithmetic. For example, in python 2.7:
>>> floor(9/4 + 3/4)
2.0
What I want is an expression that, when evaluated in a different context, yields the desired (9 + 3) / 4 = 3
.
Solutions so far:
sympy.Mul(x + 4 - 1, sympy.Pow(4, -1), evaluate=False)
sympy.factor((x + 4 - 1) / 4)
While these both give the desired (x + 3)/4
, they have to be done explicitly for every expression.
I'm looking for something along the lines of:
>>> sympy.assume_integer()
>>> (x + 4 - 1) // 4
(x + 3) / 4
Context: Our project uses SymPy to generate C++, so we generate a string from the sympy expression which needs to evaluate correctly under integer arithmetic.
Although floor(x/4 + 3/4).subs(x, 9)
indeed yields 3, this is not the context we will evaluate the expression in.
The answer here suggests something along the lines of:
>>> ((x+4-1-(x+4-1)%4)/4)
x/4 - Mod(x + 3, 4)/4 + 3/4
Which has the same issue as above, i.e. 3/4
is not an integer.