How to generate C code from the sympy expression "e1 op e2" to a C function of "if (e1<=e2) then return 0 else return 1"

33 views
Skip to first unread message

zell

unread,
Dec 7, 2015, 1:53:56 AM12/7/15
to sympy
Suppose I have a sympy expression 

e1 op e2

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

I want to generate a C code

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

where x1,...,x2 are free variables in either e1 or e2. 

How can I use sympy.printing.ccode, or sympy.utlilities.codegen to simplify this code generation? Thanks for your idea.

Aaron Meurer

unread,
Dec 7, 2015, 4:37:00 PM12/7/15
to sy...@googlegroups.com
If your result is only 0 and 1 you can use the fact that booleans are
integers in C. In this case, you would have Not(e1 <= e2) (i.e., e1 >
e2).

If you are dealing with more general numbers, see
https://github.com/sympy/sympy/pull/10209.

Aaron Meurer
> --
> You received this message because you are subscribed to the Google Groups
> "sympy" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to sympy+un...@googlegroups.com.
> To post to this group, send email to sy...@googlegroups.com.
> Visit this group at http://groups.google.com/group/sympy.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/sympy/2679496c-9d2b-40e9-8211-936b60310737%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.
Reply all
Reply to author
Forward
0 new messages