【发布时间】:2016-09-25 14:23:17
【问题描述】:
我有一个脚本可以自动生成方程式并将它们添加到列表中。
例如:
eq = [a*b, a + b*c -d, c**2 + a, d*a - 2]
带有 a、b、c、d 所有符号。
然后它将列表转换为 sympy 矩阵并计算雅可比矩阵
eq = sympy.Matrix(eq)
jacobi = eq.jacobian([a, b, c, d])
我想将这个 jacobian 保存在一个 python 文件中,以便我在另一个 python 脚本中使用它。
目前我使用字符串列表创建定义并将其写入 python 文件
variable_list = [a, b, c, d]
jacobian_lines = ["def jacobian(variables):",
' """ Returns the evaluated jacobian matrix',
' :param variables: a list of numeric values to evaluate the jacobian',
' """', '', ' {} = variables'.format(str(variable_list)), '',
' j = {}'.format(jacobi), '', " return j"]
file_path = 'jacobian.py'
file = open(file_path, 'w')
for line in jacobian_lines:
file.write('{}\n'.format(line))
有没有更正确/更好的方法来做到这一点?
【问题讨论】:
-
这是现在最好的方法。 SymPy 具有代码生成功能,目前针对 C 和 Fortran 等其他语言,但它们主要在未来获得编写 Python 代码的能力,这可能会使这类事情更容易编写。