Search code examples
pythonsympyintegralcalculus

Sympy will not compute this integral


I'm trying to run the following sample in sympy

import sympy as sp
from sympy.parsing.sympy_parser import parse_expr

n, L, x = sp.symbols('n L x')    
sp.integrate(sp.cos(sp.pi*x/L)**2, (x, -L/2, L/2))

For some reason, it does not actually solve this integral. It just prints out the original integral.

>>> sp.integrate(sp.cos(sp.pi*x/L)**2, (x, -L/2, L/2))
  L
  -
  2
  /
 |
 |     2/pi*x\
 |  cos |----| dx
 |      \ L  /
 |
/
-L
---
 2

Wolfram Alpha, on the other hand, does not have this issue.


Solution

  • It seems a bit annoying, but sympy isn't evaluating the integral because it doesn't know enough about L. Specifically, it is leaving the door open to the possibility L=0, which would wreak havoc on your integrand. To overcome this we simply need to inform sympy that L is not zero. The easiest way to do this is to pass an argument to symbols during instantiation:

    import sympy as sp
    n, x = sp.symbols('n x')    
    L = sp.symbols('L', nonzero=True)
    sp.integrate(sp.cos(sp.pi*x/L)**2, (x, -L/2, L/2))
    #>>> L/2