I had some trouble adding complex numbers in polar form in sympy. The following code
from sympy import I, exp, pi, re, im
a = exp(2*pi/3*I)
b = exp(-2*pi/3*I)
c = a+b
print(c)
print(c.simplify())
print(c.as_real_imag())
print(re(c)+im(c)*I)
print(int(c))
print(complex(c))
gives
exp(-2*I*pi/3) + exp(2*I*pi/3)
-(-1)**(1/3) + (-1)**(2/3)
(-1, 0)
-1
-1
(-1+6.776263578034403e-21j)
What I want, is to get the simplest answer to a+b
, which is -1
. I can obtain this, by manually rebuilding c=a+b
with re(c)+im(c)*I
. Why is this necessary? And is there a better way to do this?
Simply printing c
retains the polar forms, obfuscating the answer, c.simplify()
leaves the polar form, but is not really helpful, and c.as_real_imag()
returns a tuple. int(c)
does the job, but requires the knowledge, that c
is real (otherwise it throws an error) and integer (otherwise, this is not the answer I want). complex(c)
kind of works, but I don't want to leave symbolic calculation. Note, that float(c)
does not work, since complex(c)
has a non-zero imaginary part.
https://stackoverflow.com/users/9450991/oscar-benjamin has given you the solution. If you are in polar coordinates, your expression may have exponential functions. If you don't want these you have to rewrite into trigonometric functions where special values are known for many values. For example, consider a
's 2*pi/3
angle:
>>> cos(2*pi/3)
-1/2
>>> sin(2*pi/3)
sqrt(3)/2
When you rewrite a
in terms of cos
(or sin
) it becomes the sum of those two values (with I
on the sin
value):
>>> a.rewrite(cos)
-1/2 + sqrt(3)*I/2
When you rewrite a more complex expression, you will get the whole expression rewritten in that way and any terms that cancel/combine will do so (or might need some simplification):
>>> c.rewrite(cos)
-1