Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

sympy - What causes this error (AttributeError: 'Mul' object has no attribute 'cos') in 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))
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is with namespace clash, here

from sympy import *
from numpy import *

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))

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))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...