Python,sympy计算多变量函数

标签 python sympy

假设我们有两个列表:

variables = ['a','b','c'...]
values = [1,2,3...]

和一个简单的产品功能:

function = 'a*b*c*...*z'

我尝试这样做(我确实意识到它 100% 不正确,但我不知道如何将多个变量替换为 sympified expression ):

import sympy
y = sympy.sympify(function).evalf(subs={variable:values})

最佳答案

这是一个完整的例子。您只需要 zip 来混合这两个列表。来自documentation :

To perform multiple substitutions at once, pass a list of (old, new) pairs to subs.

from sympy import sympify

variables = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
values = range(1, len(variables) + 1)
expression = '*'.join(variables)
sub_table = zip(variables, values)
print values
# [1, 2, 3, 4, 5, 6, 7]
print expression
# a*b*c*d*e*f*g
print sub_table
# [('a', 1), ('b', 2), ('c', 3), ('d', 4), ('e', 5), ('f', 6), ('g', 7)]
print sympify(expression).subs(sub_table)
# 5040

作为奖励:

  • 你不需要建立一个额外的字典
  • subs() 的输出是一个精确的整数,而不仅仅是 evalf() 的一个 float 。

关于Python,sympy计算多变量函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42648920/

相关文章:

python - scipy 的 cdist 与 Sympy 符号不兼容

python - 在 python 中使用 matplotlib 绘制相似度测量圆时出错

python - KIVY语言: multiple commands in a single line

python - 处理 MongoDB 和 pymongo 中的时区日期

python - 在 Python 中将 Qt 图像转换为 Open CV 中的图像

python - sympy 求解器中的 float 与整数

python - 如何使用 Sympy `_backend` 的 `plot` 属性

python - 如何设置两个 PyPI 索引

python - SymPy 是否可以渲染 LaTeX 以在 GUI 中使用?

python - Sympy 提取傅里叶级数系数