Skip to content
Snippets Groups Projects
Commit fd5e5d2c authored by cprutean's avatar cprutean
Browse files

Upload New File

parent 1d3e3819
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id:80ff35bf tags:
# Vector
%% Cell type:code id:1bdf8ec5 tags:
``` python
""""
A more developed Vector class for simple 3d vectors
"""
import math
class Vector3d(object):
"""
Simple vector 3d class
"""
def __init__(self, x, y, z):
"""
Constructor to form a vector
"""
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __str__(self):
"""
Method to format a vector as a string (implments str())
"""
return "[" + str(self.x) + ", " + str(self.y) + ", " + str(self.z) + "]"
def copy(self):
"""
Method to return a copy of current vector
"""
return Vector3d(self.x,self.y,self.z)
def magnitude(self):
"""
Return the magnitude
"""
return math.sqrt(self.x*self.x + self.y*self.y + self.z*self.z)
def distance(self,b):
"""
Distance from self to vector b
"""
dx = self.x - b.x
dy = self.y - b.y
dz = self.z - b.z
return math.sqrt(dx*dx + dy*dy + dz*dz)
def normalise(self):
"""
Normlaise current vector so its magnitude is 1.0 (unit vector)
"""
mag = self.magnitude()
if mag != 0.0 : # if not already zero
self.x /= mag # dveive throgh by mag
self.y /= mag
self.z /= mag
def add(self,b):
"""
Add a vector b to self and return a new vector.
"""
x = self.x + b.x
y = self.y + b.y
z = self.z + b.z
return Vector3d(x,y,z)
def addTo(self,b):
"""
Add a vector b to self in place.
"""
self.x += b.x
self.y += b.y
self.z += b.z
def dot(self,b):
"""
Form dot product between self and vector b
"""
return self.x*b.x + self.y*b.y + self.z*b.z
def cross(self,b):
"""
Form cross product between self and vector b.
"""
x = self.y*b.z - self.z*b.y
y = self.z*b.x - self.x*b.z
z = self.x*b.y - self.y*b.x
return Vector3d(x,y,z)
def main():
"""
Simple test program to test the vectors
"""
a = Vector3d(1,2,3)
b = Vector3d(4,5,6)
print("Magnitde of a is " + str(a.magnitude()))
c = a.cross(b) # Form cross product
#
# the str() function call the __str__(self) method
print("Cross product of a x b is : " + str(c))
#main()
```
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment