【发布时间】: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