from sympy import cse
def simplify_and_generate_cpp_code(expr, function_name="simplified_function"):
# 提取出表达式中的重复子表达式
sub_exprs, simplified_expr = cse(expr)
# 构建 C++ 代码字符串
cpp_code = "#include <cmath>\n\n"
cpp_code += "double " + function_name + "("
# 添加函数参数
for i, (var, _) in enumerate(sub_exprs):
cpp_code += f"double {var}"
if i < len(sub_exprs) - 1:
cpp_code += ", "
cpp_code += ") {\n"
# 添加局部变量定义和初始化
for var, sub_expr_var in sub_exprs:
cpp_code += f" double {str(var)};\n"
cpp_code += "\n"
# 添加表达式赋值
for var, sub_expr in sub_exprs:
cpp_code += f" double {str(sub_expr[0])} = {str(sub_expr[1])};\n"
# 添加返回语句
cpp_code += f" return {simplified_expr};\n"
cpp_code += "}\n"
with open('funcpp.py', 'w') as file:
file.write(cpp_code)
# 示例使用
from sympy import symbols, sin, cos
# 定义一个复杂的表达式
x, y = symbols('x y')
expr = x+y+y * (x**2*(x+y))
# 调用函数进行化简并生成 Python 函数
simplified_function = simplify_and_generate_cpp_code(expr)