【问题标题】:Define function from SymPy symbols从 SymPy 符号定义函数
【发布时间】:2020-03-19 13:20:38
【问题描述】:

我正在使用 SymPy 对变量进行分析处理(例如矩阵乘法等)。 这样做之后,我最终得到了一个新的 SymPy 表达式,我想用它来使用 Matplotlib 进行绘图。到目前为止,我这样做的唯一方法是打印 SymPy 表达式并将其手动粘贴到新定义的函数中。

如何不依赖复制粘贴,直接将 SymPy 表达式转化为数值解释的函数?

一个最小的工作示例如下:

import sympy as sp
import matplotlib.pyplot as plt
import numpy as np

sp.var('x A B') # x will later be the variable, A and B will be constants
temp = A*x+B # intermediate calculations
f = temp*x # function in reality, it will be more complicated.
print(f) # I printed f in order to find the expression and copy-pasting it into the function below.

def func(x,A,B):
    return x*(A*x + B) # This statement was copy-pasted. This line should be changed, s.t. copy-pasting is not necessary!

#Now we can handle the function numerically for plotting (using matplotlib and numpy)
xspace = np.linspace(0,5)
plt.plot(xspace,func(x=xspace,A=1,B=2))

【问题讨论】:

    标签: python function numpy matplotlib sympy


    【解决方案1】:

    Sympy 的 lambdify 正是为此而存在的。只需将您对 func 的定义替换为:

    func = sp.lambdify((x,A,B),f)
    

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 2014-09-10
      • 1970-01-01
      • 2016-01-06
      • 1970-01-01
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 2023-01-11
      相关资源
      最近更新 更多