Added vector calc functions
parent
2dca458c16
commit
d2ace996da
@ -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))
|
Loading…
Reference in New Issue