Commits

German Larrain committed effd538

utils.mathematical: added 'unitize' function, and changed 'norm3' so it would call the former.

Comments (0)

Files changed (1)

ars/utils/mathematical.py

 
 def norm3(vector):
 	"""Returns the unit length 3-vector parallel to 3-vector vector"""
-	#TODO: convert it so it can handle vector of any dimension
-	l = length3(vector)
-	if l > 0.0:
-		return (vector[0] / l, vector[1] / l, vector[2] / l)
+	#l = length3(vector)
+	#if l > 0.0:
+	#	return (vector[0] / l, vector[1] / l, vector[2] / l)
+	#else:
+	#	return (0.0, 0.0, 0.0)
+	return unitize(vector)
+
+def unitize(vector_):
+	"""Unitize a vector, i.e. return a unit-length vector parallel to `vector`
+
+	"""
+	len_ = sqrt(sum(itertools.imap(operator.mul, vector_, vector_)))
+	size_ = len(vector_)
+
+	if len_ > 0.0:
+		div_vector = (len_,) * size_  # (len_, len_, len_, ...)
+		return tuple(itertools.imap(operator.div, vector_, div_vector))
 	else:
 		return (0.0, 0.0, 0.0)
 
 	return sum(itertools.imap(operator.mul, vec1, vec2))
 
 def cross_product(vector1, vector2):
-	"""Returns the cross_product product of 3-vectors vector1 and vector2"""
+	"""Returns the cross_product product of length-3 vectors `vector1` and
+	`vector2`
+
+	"""
 	return (vector1[1] * vector2[2] - vector1[2] * vector2[1],
 		vector1[2] * vector2[0] - vector1[0] * vector2[2],
 		vector1[0] * vector2[1] - vector1[1] * vector2[0])