>> (x + 4 - 1) // 4 f...">

Sympy integer arithmetic

I am trying to put an integer xdivided by a constant:

>>> x = sympy.Symbol("x", integer=True)
>>> (x + 4 - 1) // 4
floor(x/4 + 3/4)

If we choose this from the sympy context, the expression will be incorrect when accepting integer arithmetic. For example, in python 2.7:

>>> floor(9/4 + 3/4)
2.0

I want this expression, which when evaluated in a different context gives 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)

Although both of them give the desired (x + 3)/4, they must be executed explicitly for each expression.

I am looking for something like:

>>> sympy.assume_integer()
>>> (x + 4 - 1) // 4
(x + 3) / 4

Context: Our project uses Sympy to generate C ++, so we generate a string from a sympy expression that should be evaluated correctly with integer arithmetic. Although it floor(x/4 + 3/4).subs(x, 9)really gives 3, this is not the context that we will evaluate in the expression.


- :

>>> ((x+4-1-(x+4-1)%4)/4)      
x/4 - Mod(x + 3, 4)/4 + 3/4

, , .. 3/4 .

+4
2

++, Sympys, . :

from sympy.abc import x
from sympy.printing import cxxcode

expr = (x+3)//4
print(cxxcode(expr))
# 'floor((1.0L/4.0L)*x + 3.0L/4.0L)'

++:

# include <stdio.h>
# include <math.h>

int main()
{
    int x = 9;
    printf("%Lf\n", floor((1.0L/4.0L)*x + 3.0L/4.0L));
}

3.000000. .

+2

, sympy factor.

import sympy as sym
x = sym.symbols('x', integer=True)
sym.factor((x + 4 - 1) /4)

(x+3)/4. , ?

sym.floor(sym.factor((x + 4 - 1) /4))

floor((x+3)/4).

:

def arith_print(x):
    print(sym.floor(sym.factor(x)))

- , , , .

P.S.: >>> (x + 4 - 1) // 4 , sympy. 0.7.6 .

0

Source: https://habr.com/ru/post/1684883/


All Articles