Integrate in sympy doesn't work for x*cos(n*pi*x/L), but DOES work for sqrt(1.)*x*cos(n*pi*x/L). Please see code snippets below

StackOverflow https://stackoverflow.com/questions/21744623

  •  10-10-2022
  •  | 
  •  

Domanda

Code snippet 1:

from sympy import symbols, integrate, cos, pi
from numpy import sqrt
n = symbols('n', integer=True)
x, L = symbols('x L', real=True)
fs_coeff = integrate(sqrt(1.)*x*cos(n*pi*x/L), (x, 0, L))
print fs_coeff

And I get:

-1.0*Piecewise((0, n == 0), (0.101321183642338*L*2/n*2, True)) + 1.0*Piecewise((L**2/2, n == 0), (0.318309886183791*L**2*sin(3.14159265358979*n)/n + 0.101321183642338*L**2*cos(3.14159265358979*n)/n**2, True))

Code snippet 2:

from sympy import symbols, integrate, cos, pi
from numpy import sqrt
n = symbols('n', integer=True)
x, L = symbols('x L', real=True)
fs_coeff = integrate(x*cos(n*pi*x/L), (x, 0, L))
print fs_coeff

And I get an error:

Traceback (most recent call last):

File "test-sympy.py", line 6, in

fs_coeff = integrate(x*cos(n*pi*x/L), (x, 0, L))

...

ValueError: too many values to unpack

I'm using the latest Enthought Canopy python distribution, v. 1.3. Python version 2.7.6, SymPy 0.7.3.

If you have any insight on this, I'd appreciate it.

È stato utile?

Soluzione

SymPy 0.7.3 is not the newest version. Try it in 0.7.4.1. This was a bug that has been fixed.

>>> fs_coeff = integrate(x*cos(n*pi*x/L), (x, 0, L))
>>> fs_coeff
Piecewise((L**2/2, n == 0), ((-1)**n*L**2/(pi**2*n**2) - L**2/(pi**2*n**2), True))

Altri suggerimenti

The problem seems to be in the handling of the piecewise interval for n=0, which breaks when exact math is being used, but not with approximate math. The sqrt is not necessary, you can get the same result with 1.*x*cos(n*pi*x/L). Since it is unlikely you want n=0, you can get a nice clean answer by limiting n to being positive:

from sympy import symbols, integrate, cos, pi
from numpy import sqrt
n = symbols('n', integer=True, positive=True)
x, L = symbols('x L', real=True)
fs_coeff = integrate(x*cos(n*pi*x/L), (x, 0, L))
print fs_coeff
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top