Shadow43375
Shadow43375

Reputation: 604

Making SymPy symbols refer to the set of real numbers only

When working with symbols in Sympy it would sometimes be useful for the library to understand that a symbol refers only to a certain subset of the complex numbers. Example: theta = sympy.symbols('theta') when fed into the sin function and taking the complex conjugate sympy.conjugate(sympy.sin(theta)) would ideally yield sin(theta) since theta will only ever be a real number and the complex conjugate only negates the imaginary component of a complex number. Instead, it gives sin(conjugate(theta)) which indicates that sympy has no semantic understanding that theta will never have a non-zero imaginary component.

This can lead to problems since sin(theta) is not necessarily the same as sin(conjugate(theta)). Is there a way to tell SymPy that a given symbol is a real number such that sin(conjugate(theta)) automatically simplifies to sin(theta)?

Upvotes: 1

Views: 5704

Answers (1)

norok2
norok2

Reputation: 26886

You should use real=True upon declaration, i.e.:

import sympy as sym
from sympy import conjugate, sin

theta = sym.Symbol('theta', real=True)

sin(conjugate(theta))
# evaluates to: sin(theta)

conjugate(sin(theta))
# evaluates to: sin(theta)

while:

zeta = sym.Symbol('zeta')

sin(conjugate(zeta))
# evaluates to: sin(conjugate(zeta))

conjugate(sin(zeta))
# evaluates to: conjugate(sin(zeta))

if the symbol is not declared as real.

EDIT: This could be found in one of the older tutorials. I am not sure why this was not covered in newer tutorials, but as of SymPy 1.4 it works.

Upvotes: 3

Related Questions