bug in modulus?

jantod at gmail.com jantod at gmail.com
Sun Apr 23 16:33:09 EDT 2006


Hmmm. I understand. I'd suggest that someone just drop a link from the
Library reference manual as the divmod entry over there seems to
contradict it.

"""
divmod(a, b)

Take two (non complex) numbers as arguments and return a pair of
numbers consisting of their quotient and remainder when using long
division. With mixed operand types, the rules for binary arithmetic
operators apply. For plain and long integers, the result is the same as
(a / b, a % b). For floating point numbers the result is (q, a % b),
where q is usually math.floor(a / b) but may be 1 less than that. In
any case q * b + a % b is very close to a, if a % b is non-zero it has
the same sign as b, and 0 <= abs(a % b) < abs(b).
"""

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

Thanks for your help!




More information about the Python-list mailing list