#------------------------------------------------------------------------------ # vector.py #------------------------------------------------------------------------------ from math import sqrt, acos from random import uniform class Vector: """ Class representing vectors in 3-dimensional space. """ def __init__(self, x=0, y=0, z=0): """Initialize Vector """ self.components = {1:x, 2:y, 3:z} # end __init__() def __str__(self): """Return string representation of self.""" u = self.components return f'<{u[1]:.2f}, {u[2]:.2f}, {u[3]:.2f}>' # end __str__() def __eq__(self, other): """Return True if self==other, False otherwise.""" u = self.components v = other.components return ( u[1]==v[1] and u[2]==v[2] and u[3]==v[3] ) # another way: ( u==v ) # end __eq__() def add(self, other): """Return the sum of self and other.""" u = self.components v = other.components return Vector(u[1]+v[1], u[2]+v[2], u[3]+v[3]) # end add() def sub(self, other): """Return the difference of self and other.""" return self.add(other.scale(-1)) # end sub() def mult(self, other): """Return the hadamard product of self and other.""" u = self.components v = other.components return Vector(u[1]*v[1], u[2]*v[2], u[3]*v[3]) # end mult() def dot(self, other): """Return the dot product of self and other.""" u = self.components v = other.components return sum([u[1]*v[1], u[2]*v[2], u[3]*v[3]]) # end dot() def length(self): """Return the (geometric) length of self.""" return sqrt(self.dot(self)) # end length() def scale(self, c): """Return the product of self with scalar c.""" u = self.components return Vector(c*u[1], c*u[2], c*u[3]) # end scale() def unit(self): """Return a unit Vector parallel to self.""" if self.length()==0: raise ValueError('no unit vector in direction', self) # end if c = 1/self.length() return self.scale(c) # end unit() def angle(self, other): """Return the angle (in radians) between self and other.""" return acos( self.unit().dot(other.unit()) ) # end angle() def cross(self, other): """Return the cross product of self and other.""" u = self.components v = other.components x = u[2]*v[3]-u[3]*v[2] y = u[3]*v[1]-u[1]*v[3] z = u[1]*v[2]-u[2]*v[1] return Vector(x, y, z) # end cross() def tensor(self, other): """ Return the tensor product of self and other, as a list of lists. """ u = self.components v = other.components T = [] for i in [1,2,3]: R = [] for j in [1,2,3]: R.append(u[i]*v[j]) # end for T.append(R) # end for return T # end tensor() def randVector(a, b): """ Return a Vector whose components are unformily distributed random floats t satisfying a<=t<=b. """ x = uniform(a, b) y = uniform(a, b) z = uniform(a, b) return Vector(x, y, z) # end randVector() # end class Vector