]> gitweb.michael.orlitzky.com - dunshire.git/commitdiff
Add an inner_product() for matrices.
authorMichael Orlitzky <michael@orlitzky.com>
Mon, 10 Oct 2016 01:26:56 +0000 (21:26 -0400)
committerMichael Orlitzky <michael@orlitzky.com>
Mon, 10 Oct 2016 02:36:20 +0000 (22:36 -0400)
src/dunshire/matrices.py

index 7bfc429bdd5651b10e07cae79a653e1e3cc925b5..52ba2a34c0352ac9d16744c64abc5ac195a50d7e 100644 (file)
@@ -83,6 +83,37 @@ def identity(domain_dim):
     return matrix(entries, (domain_dim, domain_dim))
 
 
+def inner_product(vec1, vec2):
+    """
+    Compute the (Euclidean) inner product of the two vectors ``vec1``
+    and ``vec2``.
+
+    EXAMPLES:
+
+        >>> x = [1,2,3]
+        >>> y = [3,4,1]
+        >>> inner_product(x,y)
+        14
+
+        >>> x = matrix([1,1,1])
+        >>> y = matrix([2,3,4], (1,3))
+        >>> inner_product(x,y)
+        9
+
+        >>> x = [1,2,3]
+        >>> y = [1,1]
+        >>> inner_product(x,y)
+        Traceback (most recent call last):
+        ...
+        TypeError: the lengths of vec1 and vec2 must match
+
+    """
+    if not len(vec1) == len(vec2):
+        raise TypeError('the lengths of vec1 and vec2 must match')
+
+    return sum([x*y for (x,y) in zip(vec1,vec2)])
+
+
 def norm(matrix_or_vector):
     """
     Return the Frobenius norm of ``matrix_or_vector``, which is the same
@@ -100,7 +131,7 @@ def norm(matrix_or_vector):
         2.0
 
     """
-    return sqrt(sum([x**2 for x in matrix_or_vector]))
+    return sqrt(inner_product(matrix_or_vector,matrix_or_vector))
 
 
 def vec(real_matrix):