Created
August 29, 2018 22:48
-
-
Save rogerwelin/716928309506790f162082d731ec57e6 to your computer and use it in GitHub Desktop.
vectors python
This file contains hidden or 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
| import math | |
| def vector_add(v, w): | |
| return [v_i + w_i for v_i, w_i in zip(v, w)] | |
| def vector_subtract(v, w): | |
| return [v_i + w_i for v_i, w_i in zip(v, w)] | |
| def vector_sum(vectors): | |
| result = vectors[0] | |
| for vector in vectors[1:]: | |
| result = vector_add(result, vector) | |
| return result | |
| def scalar_multiply(c, v): | |
| return [c * v_i for v_i in v] | |
| def vector_mean(vectors): | |
| n = len(vectors) | |
| return scalar_multiply(1/n, vector_sum(vectors)) | |
| # the dot product of 2 vectors is the sum of their | |
| # componentwise products | |
| def dot(v, w): | |
| """ v_1 * w_1 + ... + v_n * w_n """ | |
| return sum(v_i * w_i for v_i, w_i in zip(v, w)) | |
| def sum_of_squares(v): | |
| """ v_1 * v_1 + ... v_n * v_n """ | |
| return dot(v, v) | |
| def magnitude(v): | |
| return math.sqrt(sum_of_squares(v)) | |
| def squared_distance(v, w): | |
| """ (v_1 - w_1) ** 2 + ... (v_n - w_n) ** 2 """ | |
| return sum_of_squares(vector_subtract(v, w)) | |
| def distance(v, w): | |
| return math.sqrt(squared_distance(v, w)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment