Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basics of SymPy

Tags:

python

sympy

I am just starting to play with SymPy and I am a bit surprised by some of its behavior, for instance this is not the results I would expect:

>>> import sympy as s
>>> (-1)**s.I == s.E**(-1* s.pi)
False
>>> s.I**s.I == s.exp(-s.pi/2)
False

Why are these returning False and is there a way to get it to convert from one way of writing a complex number to another?

like image 654
TimothyAWiseman Avatar asked Jan 23 '23 20:01

TimothyAWiseman


1 Answers

From the FAQ:

Why does SymPy say that two equal expressions are unequal?

The equality operator (==) tests whether expressions have identical form, not whether they are mathematically equivalent.

To make equality testing useful in basic cases, SymPy tries to rewrite mathematically equivalent expressions to a canonical form when evaluating them. For example, SymPy evaluates both x+x and -(-2*x) to 2*x, and x*x to x**2.

The simplest example where the default transformations fail to generate a canonical form is for nonlinear polynomials, which can be represented in both factored and expanded form. Although clearly a(1+b) = a+ab mathematically, SymPy gives:

>>> bool(a*(1+b) == a + a*b) False 

Likewise, SymPy fails to detect that the difference is zero:

 >>> bool(a*(1+b) - (a+a*b) == 0) False  

If you want to determine the mathematical equivalence of nontrivial expressions, you should apply a more advanced simplification routine to both sides of the equation. In the case of polynomials, expressions can be rewritten in a canonical form by expanding them fully. This is done using the .expand() method in SymPy:

>>> A, B = a*(1+b), a + a*b 
>>> bool(A.expand() == B.expand()) True 
>>> (A - B).expand() 0 

If .expand() does not help, try simplify(), trigsimp(), etc, which attempt more advanced transformations. For example,

>>> trigsimp(cos(x)**2 + sin(x)**2) == 1 True
like image 111
Ewan Todd Avatar answered Feb 05 '23 00:02

Ewan Todd