Advertisement
Programmin-in-Python

Vector Operations and Representations using a Vector Class

Jan 30th, 2021 (edited)
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.77 KB | None | 0 0
  1. from math import sqrt, acos, degrees as deg
  2.  
  3. class Vector:
  4.  
  5.     # Initialisation
  6.     def __init__(self, x=0, y=0, z=0):
  7.         self.__availDTypes = [int, float]
  8.  
  9.         if (type(x) in self.__availDTypes) and (type(y) in self.__availDTypes) and (type(z) in self.__availDTypes):
  10.             self.__x = x
  11.             self.__y = y
  12.             self.__z = z
  13.         else:
  14.             raise TypeError("Unsupported Data Type; Should be either int or float")
  15.  
  16.     # Getters
  17.     @property
  18.     def x(self):
  19.         return self.__x
  20.  
  21.     @property
  22.     def y(self):
  23.         return self.__y
  24.  
  25.     @property
  26.     def z(self):
  27.         return self.__z
  28.  
  29.     # Setters
  30.     @x.setter
  31.     def x(self, Int):
  32.         if type(Int) in self.__availDTypes:
  33.             self.__x = Int
  34.         else:
  35.             raise ValueError("Unsupported Data Type for Direction Ratio")
  36.  
  37.     @y.setter
  38.     def y(self, Int):
  39.         if type(Int) in self.__availDTypes:
  40.             self.__y = Int
  41.         else:
  42.             raise ValueError("Unsupported Data Type for Direction Ratio")
  43.  
  44.     @z.setter
  45.     def z(self, Int):
  46.         if type(Int) in self.__availDTypes:
  47.             self.__z = Int
  48.         else:
  49.             raise ValueError("Unsupported Data Type for Direction Ratio")
  50.  
  51.     # Arithmetic Operations
  52.     def __add__(self, other):
  53.         return Vector((self.x+other.__x),
  54.                     (self.y+other.__y),
  55.                     (self.z+other.__z))
  56.  
  57.     def __div__(self, scalar):
  58.         if not isinstance(scalar, Vector):
  59.             return Vector((self.x/scalar),
  60.                         (self.y/scalar),
  61.                         (self.z/scalar))
  62.         else:
  63.             raise TypeError("Unsupported operand type(s) for /")
  64.  
  65.     def __eq__(self, other):
  66.         if isinstance(other, Vector):
  67.             if self.directionRatios() == other.directionRatios():
  68.                 return True
  69.             else:
  70.                 return False
  71.         else:
  72.             raise TypeError("Unsupported operand type(s) for ==")
  73.  
  74.     def __mul__(self, scalar):
  75.         if not isinstance(scalar, Vector):
  76.             return Vector(round((self.x*scalar), 2),
  77.                         round((self.y*scalar), 2),
  78.                         round((self.z*scalar), 2))
  79.         else:
  80.             raise TypeError("Unsupported operand type(s) for *")
  81.  
  82.     def __sub__(self, other):
  83.         return Vector((self.x-other.__x),
  84.                     (self.y-other.__y),
  85.                     (self.z-other.__z))
  86.  
  87.     # Representation
  88.     def __repr__(self):
  89.         if (self.x < 0) or (self.y < 0) or (self.z < 0):
  90.             str_res = "<Vector Object> with "
  91.  
  92.             if self.x < 0:
  93.                 str_res += f"({self.x})i + "
  94.             else:
  95.                 str_res += f"{self.x}i + "
  96.  
  97.             if self.y < 0:
  98.                 str_res += f"({self.y})j + "
  99.             else:
  100.                 str_res += f"{self.y}j + "
  101.  
  102.             if self.z < 0:
  103.                 str_res += f"({self.z})k"
  104.             else:
  105.                 str_res += f"{self.z}k"
  106.  
  107.             return str_res
  108.         else:
  109.             return f"<Vector Object> with {self.x}i + {self.y}j + {self.z}k"
  110.  
  111.     # Cross and Dot Products
  112.     def cross(self, other):
  113.         if isinstance(other, Vector):
  114.             __X = round(((self.y*other.__z)-(other.__y*self.z)), 2)
  115.             __Y = round(((self.x*other.__z)-(other.__x*self.z)), 2)
  116.             __Z = round(((self.x*other.__y)-(other.__x*self.y)), 2)
  117.             return Vector(__X, __Y, __Z)
  118.         else:
  119.             raise TypeError("Unsupported operand type; Requires Vector Object")
  120.  
  121.     def dot(self, other):
  122.         if isinstance(other, Vector):
  123.             return round(((self.x*other.__x)+(self.y*other.__y)+(self.z*other.__z)),
  124.                         2)
  125.         else:
  126.             raise TypeError("Unsupported operand type; Requires Vector Object")
  127.  
  128.     # Direction Angles, Direction Ratios and Direction Cosines
  129.     def directionAngles(self):
  130.         __dcs = self.directionCosines()
  131.         return (deg(acos(__dcs[0])),  deg(acos(__dcs[1])), deg(acos(__dcs[2])))
  132.  
  133.     def directionCosines(self):
  134.         __mag__ = self.magnitude()
  135.         return (round((self.x/__mag__), 2),
  136.                 round((self.y/__mag__), 2),
  137.                 round((self.z/__mag__), 2))
  138.  
  139.     def directionRatios(self):
  140.         return (self.x, self.y, self.z)
  141.  
  142.     # Magnitude of a Vector
  143.     def magnitude(self):
  144.         return round(sqrt(((self.x)**2) + ((self.y)**2) + (self.z**2)), 2)
  145.  
  146.     def makesAngleWith(self, other):
  147.         if isinstance(other, Vector):
  148.             __dp, __prodmag = self.dot(other), (self.magnitude()*other.magnitude())
  149.             return round(deg(acos(round(__dp/__prodmag, 2))), 2)
  150.         else:
  151.             raise TypeError("Unsupported operand type; Requires Vector Object")
  152.  
  153.     # Projection of a Vector and Projection Vector
  154.     def projectionOn(self, other):
  155.         if isinstance(other, Vector):
  156.             __UnitOther__ = other.toUnit()
  157.             return self.dot(__UnitOther__)
  158.         else:
  159.             raise TypeError("Unsupported operand type; Requires Vector Object")
  160.  
  161.     def projectionVectorOn(self, other):
  162.         if isinstance(other, Vector):
  163.             __UnitOther__ = other.toUnit()
  164.             __projection__ = self.projectionOn(other)
  165.             return __UnitOther__ * __projection__
  166.         else:
  167.             raise TypeError("Unsupported operand type; Requires Vector Object")
  168.  
  169.     # Conversion to Unit Vector
  170.     def toUnit(self):
  171.         __mag__ = self.magnitude()
  172.         return Vector(round((self.x/__mag__), 2),
  173.                     round((self.y/__mag__), 2),
  174.                     round((self.z/__mag__), 2))
  175.  
  176.  
  177. v1 = Vector(-3, 4, 5)
  178. v2 = Vector(21, -54, -101)
  179.  
  180. print("V1 :", v1, "\nV2 :", v2)
  181.  
  182. print("\nV1 == V2 :", v1 == v2)
  183.  
  184. print("\nDirection Angles of V1 :", v1.directionAngles())
  185. print("Direction Angles of V2 :", v2.directionAngles())
  186.  
  187. print("\nDirection Ratios of V1 :", v1.directionRatios())
  188. print("Direction Ratios of V2 :", v2.directionRatios())
  189.  
  190. print("\nDirection Cosines of V1 :", v1.directionCosines())
  191. print("Direction Cosines of V2 :", v2.directionCosines())
  192.  
  193. print("\n|V1| :", v1.magnitude(), "\n|V2| :", v2.magnitude())
  194.  
  195. print("\nUnit Vector of V1 :", v1.toUnit(), "\nUnit Vector of V2 :", v2.toUnit())
  196.  
  197. print("\nV1 + V2 :", v1+v2)
  198. print("V1 - V2 :", v1-v2)
  199.  
  200. print("\nV1 * 2 :", v1*2)
  201. print("V2 * 3 :", v2*3)
  202.  
  203. print("\nV1 . V2 :",  v1.dot(v2))
  204. print("V1 X V2 :", v1.cross(v2))
  205. print("V2 X V1 :", v2.cross(v1))
  206.  
  207. print("\nAngle between V1 and V2 :", v1.makesAngleWith(v2))
  208.  
  209. print("\nProjection Vector of V1 on V2 :", v1.projectionVectorOn(v2))
  210. print("Projection Vector of V2 on V1 :", v2.projectionVectorOn(v1))
  211.  
  212. print("\nProjection of V1 on V2 :", v1.projectionOn(v2))
  213. print("Projection of V2 on V1 :", v2.projectionOn(v1))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement