Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy: C code from logical expression

From a sympy logical expression, I would like to get the equivalent C code. First off, I noticed that you cannot use the native logical operators like and and or because sympy somehow strips them off. Fair enough, there's & and friends. I tried

from sympy import *
from sympy.utilities.codegen import codegen

x = Symbol('x')
is_valid = Symbol('is_valid')

# f = x > 0 and is_valid  # TypeError: cannot determine truth value of
f = (x > 0) & is_valid  # And(is_valid, x > 0)

# TypeError: The first argument must be a sympy expression.
[(c_name, c_code), (h_name, c_header)] = codegen(("f", f), "C")

but for some reason, I'm getting

TypeError: The first argument must be a sympy expression.

Any hints?

like image 247
Nico Schlömer Avatar asked Apr 16 '26 11:04

Nico Schlömer


1 Answers

The error message is based on a hard-coded isinstance check. If it is removed, I get

#include "f.h"
#include <math.h>

double f(double is_valid, double x) {

   double f_result;
   f_result = is_valid && x > 0;
   return f_result;

}

Note however that this is still probably not what you want, since is_valid is set as a double, and you probably want it to be an int (or C99 bool).

My suggestion: use ccode on your expression directly, and write the function wrapper manually. You could also use pycodeexport if you need something more scalable.

like image 102
asmeurer Avatar answered Apr 18 '26 01:04

asmeurer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!