从SymPy符号定义函数

2024-09-24 22:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Symphy进行变量的分析处理(例如矩阵乘法等)。 完成此操作后,我将得到一个新的Symphy表达式,我希望使用Matplotlib进行绘图。到目前为止,我唯一的方法是打印Symphy表达式并手动将其粘贴到新定义的函数中

如何在不依赖复制和粘贴的情况下直接将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))

Tags: andthe函数importmatplotlib表达式粘贴as