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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.