Sympy到numpy会导致AttributeError:'Symbol'对象没有属性'cos' [英] Sympy to numpy causes the AttributeError: 'Symbol' object has no attribute 'cos'

查看:782
本文介绍了Sympy到numpy会导致AttributeError:'Symbol'对象没有属性'cos'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用sympy进行偏导数,我想将其转换为函数,以便我可以替换值并在t_1,t_2的某些值处估计导数.我正在使用的代码如下:

I am trying to do partial derivatives using sympy and I want to convert it to a function so that I can substitute values and estimate the derivatives at some values of t_1, t_2. The code I am using is as follows:

import sympy as sp
import numpy as np
from sympy import init_printing
init_printing()
t_1,t_2,X_1,X_2,Y_1,Y_2,X_c1,X_c2,Y_c1,Y_c2,a_1,a_2,psi_1,psi_2,b_1,b_2= sp.symbols('t_1 t_2 X_1 X_2 Y_1 Y_2 X_c1 X_c2 Y_c1 Y_c2 a_1 a_2 psi_1 psi_2 b_1 b_2')

X_1=X_c1 + (a_1 * sp.cos(t_1) * sp.cos(psi_1)) - ((b_1) * sp.sin(t_1)* sp.sin(psi_1))

X_2=X_c2 + (a_2 * sp.cos(t_2) * sp.cos(psi_2)) - ((b_2) * sp.sin(t_2)* sp.sin(psi_2))

Y_1=Y_c1 + (a_1 * sp.cos(t_1) * sp.sin(psi_1)) + ((b_1) * sp.sin(t_1)* sp.cos(psi_1))

Y_2=Y_c2 + (a_2 * sp.cos(t_2) * sp.sin(psi_2)) + ((b_2) * sp.sin(t_2)* sp.sin(psi_2))

D=(((X_2-X_1)**2) + ((Y_2-Y_1)**2))**0.5

y_1=sp.diff(D,t_1)

y_2=sp.diff(D,t_2)

f=sp.lambdify(t_1, y_1, "numpy")

g=sp.lambdify(t_2, y_2, "numpy")

当我尝试用代替t_1的值时,

When I try to substitute a value for t_1 using,

f(np.pi/2)

我收到以下错误:

AttributeError   Traceback (most recent call last)
<ipython-input-26-f37892b21c8b> in <module>()
----> 1 f(np.pi/2)

/users/vishnu/anaconda3/lib/python3.5/site-packages/numpy    /__init__.py in <lambda>(_Dummy_23)

AttributeError: 'Symbol' object has no attribute 'cos'

我提到了以下链接:

导致此错误的原因( AttributeError:"Mul"对象在Python中没有属性"cos")吗?

Python AttributeError:cos

但是我认为我的numpy和sympy的导入不会发生冲突,这与那些链接中提到的情况不同.感谢您的帮助.

but I think my imports of numpy and sympy are not clashing unlike the cases mentioned in those links. Any help is appreciated.

推荐答案

当您调用np.cos(a_symbol)时,会发生这种类型的错误,这显然会将numpy中的后台转换为a_symbol.cos().

This type of error occurs when you call np.cos(a_symbol), which apparently translates under-the-hood in numpy to a_symbol.cos().

lambdify用于数值计算-将所有sp调用替换为np调用.但是,您所做的只是象征性的.这足以解决您的问题:

lambdify is for numeric calculations - it replaces all sp calls with np calls. But what you're doing is symbolic. This is enough for your problem:

f1 = lambda t: y_1.subs({t_1: t})
f2 = lambda t: y_2.subs({t_2: t})

这篇关于Sympy到numpy会导致AttributeError:'Symbol'对象没有属性'cos'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆