简体   繁体   English

Sympy:来自逻辑表达式的C代码

[英]Sympy: C code from logical expression

From a sympy logical expression, I would like to get the equivalent C code. 从一个同情的逻辑表达式,我想获得等效的C代码。 First off, I noticed that you cannot use the native logical operators like and and or because sympy somehow strips them off. 首先,我注意到你不能使用像and那样的本机逻辑运算符, or因为sympy以某种方式将它们剥离。 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. TypeError:第一个参数必须是sympy表达式。

Any hints? 任何提示?

The error message is based on a hard-coded isinstance check. 错误消息基于硬编码的isinstance检查。 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). 但请注意,这仍然可能不是你想要的,因为is_valid被设置为double,你可能希望它是一个int(或C99 bool)。

My suggestion: use ccode on your expression directly, and write the function wrapper manually. 我的建议:直接在表达式上使用ccode ,并手动编写函数包装器。 You could also use pycodeexport if you need something more scalable. 如果您需要更具可扩展性的东西,也可以使用pycodeexport

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM