TAGS :Viewed: 9 - Published at: a few seconds ago

[ Generate C code for sympy expression "e1 op e2" where op is an arithmetic comparison operator ]

Suppose I have a sympy expression

e1 op e2

where op is any arithmetic comparison operator, such as <, >, <=, etc.

I want to generate a C code

double f(double x1,double x2,..., double xn){
  if (e1 op e2) return 0 else return 1;
}

where x1,...,x2 are the free variables in either e1 or e2. Can I use sympy.printing.ccode, or sympy.utlilities.codegen to simplify this code generation?

Answer 1


Here is an example using ccode and Piecewise (you would need to provide the function body as a template):

>>> from sympy import symbols, Piecewise, ccode
>>> x, y, z = symbols('x y z')
>>> e1 = x + 2
>>> e2 = y - 5
>>> rel = e1 < e2
>>> pw = Piecewise((0, rel), (1, True))
>>> print(ccode(pw, assign_to=z))
if (x + 2 < y - 5) {
   z = 0;
}
else {
   z = 1;
}