[ SKILL_DOCUMENTATION ]
# SymPy 代码生成与打印
本文档涵盖了 SymPy 生成多种语言可执行代码、将表达式转换为不同输出格式以及自定义打印行为的功能。
## 代码生成
### 转换为 NumPy 函数
python
from sympy import symbols, sin, cos, lambdify
import numpy as np
x, y = symbols('x y')
expr = sin(x) + cos(y)
# 创建 NumPy 函数
f = lambdify((x, y), expr, 'numpy')
# 与 NumPy 数组配合使用
x_vals = np.linspace(0, 2*np.pi, 100)
y_vals = np.linspace(0, 2*np.pi, 100)
result = f(x_vals, y_vals)
### Lambdify 选项
python
from sympy import lambdify, exp, sqrt
# 不同的后端
f_numpy = lambdify(x, expr, 'numpy') # NumPy
f_scipy = lambdify(x, expr, 'scipy') # SciPy
f_mpmath = lambdify(x, expr, 'mpmath') # mpmath (任意精度)
f_math = lambdify(x, expr, 'math') # Python math 模块
# 自定义函数映射
custom_funcs = {'sin': lambda x: x} # 将 sin 替换为恒等函数
f = lambdify(x, sin(x), modules=[custom_funcs, 'numpy'])
# 多个表达式
exprs = [x**2, x**3, x**4]
f = lambdify(x, exprs, 'numpy')
# 返回结果元组
### 生成 C/C++ 代码
python
from sympy.utilities.codegen import codegen
from sympy import symbols
x, y = symbols('x y')
expr = x**2 + y**2
# 生成 C 代码
[(c_name, c_code), (h_name, h_header)] = codegen(
('distance_squared', expr),
'C',
header=False,
empty=False
)
print(c_code)
# 输出有效的 C 函数
### 生成 Fortran 代码
python
from sympy.utilities.codegen import codegen
[(f_name, f_code), (h_name, h_interface)] = codegen(
('my_function', expr),
'F95', # Fortran 95
header=False
)
print(f_code)
### 高级代码生成
python
from sympy.utilities.codegen import CCodeGen, make_routine
from sympy import MatrixSymbol, Matrix
# 矩阵运算
A = MatrixSymbol('A', 3, 3)
expr = A + A.T
# 创建例程
routine = make_routine('matrix_sum', expr)
# 生成代码
gen = CCodeGen()
code = gen.write([routine], prefix='my_module')
### 代码打印器
python
from sympy.printing.c import C99CodePrinter, C89CodePrinter
from sympy.printing.fortran import FCodePrinter
from sympy.printing.cxx import CXX11CodePrinter
# C 代码
c_printer = C99CodePrinter()
c_code = c_printer.doprint(expr)
# Fortran 代码
f_printer = FCodePrinter()
f_code = f_printer.doprint(expr)
# C++ 代码
cxx_printer = CXX11CodePrinter()
cxx_code = cxx_prin