首页 > 解决方案 > 从 SymPy 符号定义函数

问题描述

我正在使用 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))

标签: pythonfunctionnumpymatplotlibsympy

解决方案


Sympylambdify正是为此而存在的。只需将您的定义替换为func

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

推荐阅读