在 Python 中是什么导致了这个错误(AttributeError: 'Mul' object has no attribute 'cos')? [英] What causes this error (AttributeError: 'Mul' object has no attribute 'cos') in Python?
问题描述
我在 Python 中尝试计算定积分时收到以下错误代码.
I am getting the following error code when trying to evaluate a definite integral in Python.
AttributeError Traceback (most recent call last)
<ipython-input-7-2be8718c68ec> in <module>()
7 x, n = symbols('x n')
8
----> 9 f = (cos(n*x))*(x**2-pi**2)^2
10 integrate(f,(x,-n*pi,n*pi))
11
AttributeError: 'Mul' object has no attribute 'cos'
我已在下面复制了我的输入代码.感谢您的帮助.
I have copied my input code below. Thanks for any help.
from pylab import *
from sympy import *
from numpy import *
init_printing(use_unicode=False, wrap_line=False, no_global=True)
x, n = symbols('x n')
f = (cos(n*x))*(x**2-pi**2)^2
integrate(f,(x,-n*pi,n*pi))
推荐答案
你的问题是命名空间冲突,在这里
Your problem is with namespace clash, here
from sympy import *
from numpy import *
因为 numpy
和 sympy
都有自己的 cos
定义.该错误告诉您 Mul
对象(即 n*x
)没有余弦方法,因为解释器现在在 sympy
和 numpy
方法.改为这样做
Since both numpy
and and sympy
have their own definition of cos
. The error is telling you that the Mul
object (which is n*x
) does not have a cosine method, since the interpreter is now confused between the sympy
and numpy
methods. Do this instead
import pylab as pl
import numpy as np
import sympy as sp
x, n = sp.symbols('x n')
f = (sp.cos(n*x))*(x**2-sp.pi**2)**2
sp.integrate(f,(x,-n*sp.pi,n*sp.pi))
另请注意,我已将 ^
更改为 **
因为 ^
是 Not
运算符在 >同情
.在这里,我假设您需要来自 sympy.core.numbers.Pi
的符号 Pi
而不是来自 numpy
的数字.如果你想要后者,那么就这样做
Also note that I have changed ^
to **
as ^
is the Not
operator in sympy
. Here, I am assuming that you need the symbolic Pi
from sympy.core.numbers.Pi
and not the numeric one from numpy
. If you want the latter, then do this
f = (sp.cos(n*x))*(x**2-np.pi**2)**2
sp.integrate(f,(x,-n*np.pi,n*np.pi))
这篇关于在 Python 中是什么导致了这个错误(AttributeError: 'Mul' object has no attribute 'cos')?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!