Created
November 15, 2017 21:37
-
-
Save fenimore/f2c9494cad14c55731af3ed86bf4954f to your computer and use it in GitHub Desktop.
linear algebra
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Vector(object): | |
def __init__(self, coords): | |
self.coordinates = coords | |
self.dimensions = len(coords) | |
def __str__(self): | |
return "Vector: {}".format(self.coordinates) | |
def __eq__(self, v): | |
return self.coordinates == v.coordinates | |
def add_vectors(*vecs): # of variable length :) | |
largest = max([v.dimensions for v in vecs]) | |
result = [0] * largest | |
for v in vecs: | |
for idx, p in enumerate(v.coordinates): | |
result[idx] += p | |
return Vector(result) | |
def sub_vectors(*vecs): | |
largest = max([v.dimensions for v in vecs]) | |
result = [0] * largest | |
for idx, p in enumerate(vecs[0].coordinates): | |
result[idx] = p | |
vecs = vecs[1:] | |
for v in vecs: | |
for idx, p in enumerate(v.coordinates): | |
result[idx] -= p | |
return Vector(result) | |
def scale_vector(scalar, vec): | |
result = [0] * vec.dimensions | |
for idx, p in enumerate(vec.coordinates): | |
result[idx] = p * scalar | |
return Vector(result) | |
if __name__ == "__main__": | |
y = Vector([-11, 3, 4]) | |
x = Vector([-1, 2, 6, 0]) | |
w = Vector([1, 5, 2, 19]) | |
print(add_vectors(x, y, w)) | |
w = Vector([1, 5, 2, 19]) | |
x = Vector([1, 2, 6, 0]) | |
y = Vector([1, 3, 4]) | |
print(sub_vectors(w, x, y)) | |
y = Vector([1, 3, 4]) | |
s = .5 | |
print(scale_vector(s, y)) | |
print("QUESTION 1") | |
print(add_vectors(Vector([8.218, -9.341]), Vector([-1.129, 2.111]))) | |
print(sub_vectors(Vector([7.119, 8.215]), Vector([-8.223, 0.878]))) | |
print(scale_vector(7.41, Vector([1.671, -1.012, -0.318]))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment