What causes this error (AttributeError: ‘Mul’ object has no attribute ‘cos’) in Python?

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

Leave a Comment