How to simplify expression for complex constant using sympy?

I did some calculations in sympy, and the result is, after all, a set of constants. One of them is inserted directly into the fragment below:

from sympy import * expr = (18**(Rational(1, 3))/(6*(3 + sqrt(3)*I)**(Rational(1, 3))) + 12**(Rational(1, 3))*(3 + sqrt(3)*I)**(Rational(1, 3))/12) print(expr.evalf()) print(expr.simplify()) 

It returns

 0.56857902130163 + 0.e-22*I 18**(1/3)/(6*(3 + sqrt(3)*I)**(1/3)) + (36 + 12*sqrt(3)*I)**(1/3)/12 

therefore, the expression appears to be a real number, but sympy cannot simplify it. With pen and paper, I simplified this for

 cos(pi/18) / sqrt(3) 

which is consistent with the numerical value returned by evalf() .

I tried many of the various simplification functions, but none of them seem to be able to reduce the expression. Using Type Substitutions

 expr.subs(3 + sqrt(3)*I, sqrt(12) * exp(I*pi/6)) 

improves expression, but simplex cannot conclude that it is real. Using Euler’s formula for substitution,

 expr.subs(3 + sqrt(3)*I, sqrt(12) * (cos(pi/6) + I*sin(pi/6))) 

sympy may finally conclude that the expression is real, but the expression itself explodes in size when printed (even if I try to simplify after the substitution).

Is there a better way to try to reduce this? I have many similar expressions for complex constants that I would like to know for sure are real (or not).

+4
source share
2 answers

For the expression you specified, the command

 (expr.conjugate().conjugate() - expr.conjugate()).simplify() 

returns 0, which means expr is real. (The double application of conjugation returns to the original value, but it expands along the way, which makes it possible to simplify it later.) In the general case, the above formula returns the imaginary part times 2i.

To find the real part of an expression, you can use a similar trick: add it to its conjugation and simplify (and divide by 2):

 ((expr.conjugate().conjugate()+expr.conjugate())/2).simplify() 

returns sqrt(3)*cos(pi/18)/3 .

+4
source

The as_real_imag method often helps to simplify a complex number, even if it is not specified in the simplification methods. In your example

 expr.as_real_imag() 

returns (sqrt(3)*cos(pi/18)/3, 0)

If a complex number is required (and not a tuple, as indicated above), you should not just call complex on this tuple, as this will create an object of the Python complex class, including a numerical estimate. I will write instead

 pair = expr.as_real_imag() result = pair[0] + pair[1]*I 
+2
source

All Articles