简体   繁体   English

sympy:将函数替换为表达式

[英]sympy: substitute function into expression

I have a 2D curve rho(t) 我有2D曲线rho(t)

import sympy as sy

t = sy.Symbol('t', is_real=True) # curve parameter
rho_x = sy.Function('rho_x', is_real=True)(t)
rho_y = sy.Function('rho_y', is_real=True)(t) # components
rho = sy.Matrix([rho_x, rho_y]) # curve vector
tau = rho.diff() / rho.diff().norm() # tangent

after that I want to evaluate parameters of the curve for a specific realization: 之后,我想评估曲线的参数以实现特定的实现:

real_shape = {rho_x: sy.sin(t), rho_y: sy.cos(t)}
f1 = tau.subs(real_shape)
print f1
f2 = sy.lambdify(t, f1)
print f2(0.1)

I found that SymPy does not evaluate the derivatives of sine and cosine functions automatically, and after calling print f2(0.1) it shows error message: 我发现SymPy不会自动评估正弦和余弦函数的导数,并且在调用print f2(0.1)会显示错误消息:

NameError: global name 'Derivative' is not defined NameError:未定义全局名称“衍生”

What is wrong in my example? 我的例子有什么问题?

You can call doit() on the Matrix to evaluate it. 您可以在矩阵上调用doit()进行评估。

In [49]: f1 = f1.doit()

In [50]: f2 = lambdify(t, f1)

In [51]: print f2(0.1)
[[ 0.99500417]
 [-0.09983342]]

Also note that you are putting assumptions wrong way. 还要注意,您以错误的方式进行了假设。 Real assumption on t should be put like this: 关于t真实假设应如下所示:

In [52]: t = Symbol('t', real=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM