python - 从 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))
解决方案
Sympylambdify
正是为此而存在的。只需将您的定义替换为func
:
func = sp.lambdify((x,A,B),f)
推荐阅读
- mysql - Mysql - 在没有唯一键的情况下插入多个唯一行
- css - Laravel Mix 在 app.css 包中不包含 bootswatch
- c# - 需要有关如何在项目中使用数据库中的表的帮助
- php - PDO - 绑定变量数量错误
- clojure - Clojure 中发生的 ClassCastExpection
- python - 如何将 tf-idf 转换为实数
- mysql - 如何在 SQL 中应用“group by”找到同一列的差异?
- installation - 如何在 Inno Setup UninstalledAll 消息中使用 {app} 路径名?
- java - 为什么我们在 Java 的 main 函数中使用 String 数组?
- python - 如何创建循环以纠正数据帧中的性别