[EMAIL PROTECTED] wrote:
> But maybe I'm reading it wrong. In any case what I wanted was simply a
> way to extract the angle from a complex number where the angle is
> between 0 and 2*pi. I think I'll just take the modulus twice.
>
> def angle(complex):
>       """Returns angle where 2*pi > angle >=0
>
>               >>> angle(1+1j) - atan(1) < 1e-3
>               True
>               >>> angle(-1+1j) - (atan(-1) + 3*pi) % (2*pi) < 1e-3
>               True
>               >>> angle(0+1j) == pi/2
>               True
>               >>> angle(0-1j) == 1.5*pi
>               True
>               >>> angle(1+0j) == 0
>               True
>               >>> angle(0+0j) == 0
>               True
>               >>> angle(1-1e-100*1j) == 0
>               True
>       """
>       if complex.real == 0:
>               if complex.imag == 0:
>                       return 0
>               if complex.imag < 0:
>                       return 1.5*pi
>               return pi/2
>       theta = (atan2(complex.imag, complex.real) % (2*pi)) % (2*pi)
>       assert 2*pi > theta >=0, (theta, complex)
>       return theta
>


from math import atan2, pi

def cangle(z):
    ret = atan2(z.imag, z.real)
    if ret < 0:
        ret += 2*pi
    return ret

assert cangle(1+1j) * 180 / pi == 45.0
assert cangle(-1+1j) * 180 / pi == 135.0
assert cangle(-1-1j) * 180 / pi == 225.0
assert cangle(1-1j) * 180 / pi == 315.0
assert cangle(1+0j) * 180 / pi == 0.0
assert cangle(-1+0j) * 180 / pi == 180.0
assert cangle(1j) * 180 / pi == 90.0
assert cangle(-1j) * 180 / pi == 270.0

Gerard

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to