Skip to content

Instantly share code, notes, and snippets.

@cole-wilson
Created August 29, 2024 00:09
Show Gist options
  • Save cole-wilson/622f02ecbc1c298b9b7de620637f7f88 to your computer and use it in GitHub Desktop.
Save cole-wilson/622f02ecbc1c298b9b7de620637f7f88 to your computer and use it in GitHub Desktop.
Extra Credit 1: MATH 273 Calculus III
# Cole Wilson
# August 28 2024
# MATH 273 Remaley Section 3
#
# Calculates the cross product of
# two vectors in 3D space, with additional
# support for many other vector and matrix
# operations such as dot products and
# scalar multiplication
class Vector:
""""""
components = []
def __init__(self, a, b, c):
"""create a 3D Vector <a, b, c>"""
self.components = [a, b, c]
def __repr__(self):
"""formats a Vector into a human readable string"""
string = ", ".join(map(str, self.components))
return f"<{string}>"
def __add__(self, b):
"""handles this Vector + another Vector b"""
return Vector(self[0]+b[0], self[1]+b[1], self[2]+b[2])
def __sub__(self, b):
"""handles this Vector - another Vector b"""
return Vector(self[0]-b[0], self[1]-b[1], self[2]-b[2])
def __mul__(self, b):
"""dot or scalar product with another Vector b or a scalar"""
if isinstance(b, Vector): # b is a Vector
return (self[0]*b[0]) + (self[1]*b[1]) + (self[2]*b[2])
else: # b is a scalar
return Vector(self[0]*b, self[1]*b, self[2]*b)
def __getitem__(self, i):
return self.components[i]
def __setitem__(self, i, value):
self.components[i] = value
def __eq__(self, b):
return self.components == b.components
class Matrix:
components = []
order = 0
def __init__(self, components):
self.components = components
assert len(components) == len(components[0]), "rows and columns must be equal"
self.order = len(components)
def det(self):
"""determinant of the Matrix (implemented for 2x2 and 3x3 matrices)"""
if self.order == 3:
A = self[0, 0] * Matrix([[self[1, 1], self[1, 2]],
[self[2, 1], self[2, 2]]]).det()
B = self[0, 1] * Matrix([[self[1, 0], self[1, 2]],
[self[2, 0], self[2, 2]]]).det()
C = self[0, 2] * Matrix([[self[1, 0], self[1, 1]],
[self[2, 0], self[2, 1]]]).det()
return A - B + C
elif self.order == 2:
return (self[0,0]*self[1,1]) - (self[0,1]*self[1,0])
def __getitem__(self, rc):
row, col = rc
return self.components[row][col]
# get the inputs from the user, and format them into Vector objects
v = Vector(*map(float, input("v = ").replace(" ","").strip("<").strip(">").split(",")))
w = Vector(*map(float, input("w = ").replace(" ","").strip("<").strip(">").split(",")))
# create the unit vectors
i = Vector(1, 0, 0)
j = Vector(0, 1, 0)
k = Vector(0, 0, 1)
# create a 3x3 Matrix containing the unit vectors and v and w
cross_product_matrix = Matrix([[ i, j, k ],
[ v[0], v[1], v[2] ],
[ w[0], w[1], w[2] ]])
# find the determinant of the 3x3 Matrix
uxw = cross_product_matrix.det()
# show the user the answer
print(f"\nu \u00d7 w = {uxw}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment