0

so I'm trying to solve this equation in Python 2.7: An = 2/T * integrate(f(t) * cos(wnt) dt), 0, T)

from sympy import *
import scipy.integrate as integrate

T = 2*pi
w = (2*pi)/T
n = Symbol("n")

An = (2/T) * (integrate.quad(lambda t:pi*t*cos(w*n*t),0,pi)[0] + integrate.quad(lambda t:0*cos(w*n*t),pi,2*pi)[0])
print(An)

However, when I run this code, I get this error.

Traceback (most recent call last):
  File "C:/Users/spide_000/PycharmProjects/CursoPython/Ejercicios/quiz2.py", line 9, in <module>
    An = (2/T) * (integrate.quad(lambda t:pi*t*cos(w*n*t),0,pi)[0] + integrate.quad(lambda t:0*cos(w*n*t),pi,2*pi)[0])
  File "C:\Python27\lib\site-packages\scipy\integrate\quadpack.py", line 341, in quad
    points)
  File "C:\Python27\lib\site-packages\scipy\integrate\quadpack.py", line 448, in _quad
    return _quadpack._qagse(func,a,b,args,full_output,epsabs,epsrel,limit)
  File "C:\Python27\lib\site-packages\sympy\core\expr.py", line 325, in __float__
    raise TypeError("can't convert expression to float")
TypeError: can't convert expression to float

I believe the problem is the "n" value there. How can I make it a non-numerical value but a constant?

I'd like to get a result like this: https://www.wolframalpha.com/input/?i=2%2F%282*pi%29++integrate%28pitcos%28wn*t%29+from+0+to+pi%29+%2B+integrate%280*cos%28wnt%29+from+pi+to+2*pi%29

Thanks!

Andrés
  • 1
  • 1
  • 2 points. 1 (off-topic), python2 does not support braces in `print`, so your `print(An)` is not correct expression in python 2 (it is correct in python3, but not in python2). Second point: probably this discussion will help you to find out the root of the problem: https://stackoverflow.com/questions/22555056/typeerror-cant-convert-expression-to-float – Rafael Feb 24 '20 at 05:54
  • Thank you! I saw that discussion before but it seems that I don't have the same case. Solution over there was to use the constants from the scipy.constants or the sympy units, but I am not using a constant like Pi or e, I'm using "n" to represent a number that goes with the variable. Like in cos(nx), and its integral being (1/n)(sen (nx)) + C. I need something like that. Any ideas? – Andrés Feb 24 '20 at 13:41

0 Answers0