Azmyin Md. Kamal
Azmyin Md. Kamal

Reputation: 91

Why doesn't sympy evaluate sin(n* pi) = 0 and cos(n * pi) = (-1)^n when n is defined to be positive integers?

When trying to evaluate a function f(x) with Sympy, the final output appears to keep sin(n * pi) and cos (n * pi) in symbolic form but does not evaluate them as 0 and (-1)^n respectively when n is defined to be positive integers. However, Symbolab appears to be able to do the above behavior.

Is there a way to get Sympy evaluate expression similar to what Symbolab does?

Minimal example to generate the behavior in Sympy

# Load libraries
import sympy as sp
from sympy import*
from IPython.display import display
init_printing()

# To turn off bugging warnings
import warnings
warnings.filterwarnings('ignore')
x,L,pi = symbols('x, L, pi', real = True, positive = true)
n = symbols('n', positive = True, integer=True)

a_n_x = 2/L
a_n_in = x * cos((n*pi*x)/L)
display(a_n_in)
a_n = a_n_x * integrate(a_n_in, (x,0,2))
display(a_n)
a_n = a_n.subs(L,2)
display(a_n)

Upvotes: 2

Views: 1743

Answers (3)

Azmyin Md. Kamal
Azmyin Md. Kamal

Reputation: 91

In order to get the desired result, we have to use sympy.cos() and sympy.pi. The updated minimal reproduceable example demonstrates this convention in further details

# Load libraries
import sympy as sp
from sympy import*
from IPython.display import display
init_printing()

# To turn off bugging warnings
import warnings
warnings.filterwarnings('ignore')
x,L = symbols('x, L', real = True, positive = True)
n = symbols('n', positive = True, integer=True)

a_n_x = 2/L
a_n_in = x * sp.cos((n*pi*x)/L)
display(a_n_in)
a_n = a_n_x * integrate(a_n_in, (x,0,2))
display(a_n)
a_n = a_n.subs(L,2)
display(a_n.simplify())

EDIT: 12/4/2021 based on detailed explanation of how pi is defined in SymPy by @kaya3

Upvotes: 0

kaya3
kaya3

Reputation: 51132

The problem is on this line:

x,L,pi = symbols('x, L, pi', real = True, positive = true)

This defines pi as a positive real variable, so it is treated just like any other positive real variable would be - in particular, sin(n * pi) and cos(n * pi) cannot be simplified, any more than sin(n * x) or cos(n * x) could be. The fact that you named it pi doesn't matter.

To fix it, use the symbol pi defined in the sympy module itself, which SymPy understands to mean the constant π. This is already imported in the line from sympy import *, so you just need to not replace it with your own variable.

Upvotes: 3

Dominic Price
Dominic Price

Reputation: 1146

You need to ensure n is an integer, otherwise the identity does not hold:

n = symbols('n', integer=True)
trigsimp( cos(pi * n) ) # Prints (-1)**n

Upvotes: 1

Related Questions