From d2ace996da361c23658efc1e9fdcdc90a0c1a52f Mon Sep 17 00:00:00 2001 From: androiddrew Date: Sun, 3 Mar 2019 20:54:33 -0500 Subject: [PATCH] Added vector calc functions --- ch4/__init__.py | 0 ch4/vector.py | 78 +++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+) create mode 100644 ch4/__init__.py create mode 100644 ch4/vector.py diff --git a/ch4/__init__.py b/ch4/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/ch4/vector.py b/ch4/vector.py new file mode 100644 index 0000000..7746514 --- /dev/null +++ b/ch4/vector.py @@ -0,0 +1,78 @@ +""" +Lists as Vectors is actually not that performant. Numpy gives all of these features straight out of the box. +""" +import math +from typing import List +from functools import reduce + + +def vector_add(v: List[float], w: List[float]) -> List[float]: + """Adds corresponding elements of two Vectors.""" + return [v_i + w_i + for v_i, w_i in zip(v, w)] + + +def vector_subtract(v: List[float], w: List[float]) -> List[float]: + """Subtracts corresponding elements of two Vectors.""" + return [v_i - w_i + for v_i, w_i in zip(v, w)] + + +def vector_sum(vectors: List[List[float]]) -> List[float]: + """Sums all corresponding elements.""" + # result = vectors[0] + # for vector in vectors[1:0]: + # result = vector_add(result, vector) + # return result + return reduce(vector_add, vectors) + + +def scalar_multiple(c: float, v: List[float]) -> List[float]: + """Scales a vector by a multiplier.""" + return [c * vi for vi in v] + + +def vector_mean(vectors) -> List[float]: + """Compute the vector whose ith element is the mean of the ith element + of the input vectors. + + Allows us to calculate the component-wise means of a list of (same-sized) + vectors. + """ + n = len(vectors) + return scalar_multiple(1 / n, vector_sum(vectors)) + + +def dot_product(v: List[float], w: List[float]) -> float: + """The dot product of two vectors is the sum of their component wise + products. + + The dot product measures how far vector v extends in the w direction. + """ + return sum(v_i * w_i for v_i, w_i in zip(v, w)) + + +def sum_of_squares(v: List[float]) -> float: + return dot_product(v, v) + + +def magnitude(v: List[float]) -> float: + """Calculates the magnitude (length) of a vector. + + The pythagorean theorem a**2 + b**2 = c**2 actually is an example + of calculating the magnitude of a vector of length 2. + """ + return math.sqrt(sum_of_squares(v)) + + +# def squared_distance(v: List[float], w: List[float]) -> float: +# """Calculates t +# +# """ +# return sum_of_squares(vector_subtract(v, w)) + + +def vector_distance(v: List[float], w: List[float]) -> float: + """Calculates the distance between vectors.""" + # return math.sqrt(squared_distance(v, w)) + return magnitude(vector_subtract(v, w))