Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sympy allows definition of integer symbols but does not account for their behavior

Tags:

python

sympy

I have the following set of commands to do a definite integral

n [2]: from sympy import *
init_printing()

x,L = symbols('x, L')
n = symbols('n', integer = True)

exp = sin((n+Rational(1,2))*pi*x/L)**2
integrate(exp, (x,0,L))

The result of these commands shown below:

enter image description here

The first result implies that n=-1/2 which implies that n is not an integer. What is the point of giving an integer attribute to the symbol if it doesn't account for it in operations as shown above? How can I force sympy to recognize that the first part of the piecewise result is impossible if n is integer?

like image 945
user32882 Avatar asked May 12 '17 06:05

user32882


1 Answers

If the equality had evaluated, this condition would have been rejected and the Piecewise would have evaluated to your expected result. Because SymPy didn't know if your L was zero or not, it couldn't evaluate that equality.

So try

>>> n = var('n', integer=True)
>>> L = var('L', nonzero=True)
>>> exp = sin((n+Rational(1,2))*pi*x/L)**2
>>> integrate(exp, (x,0,L))
L/2

And there you go! :-) (Note, however, that it should have been sufficient to just say that L was finite to know that the equality could never be true, but SymPy fails to evaluate that condition, too.)

/c

like image 58
smichr Avatar answered Oct 17 '22 08:10

smichr