Sep 2, 2016

Vector Arithmetic in Python : Dot product and Cross product

Write a sample program to perform Addition(+), Subtraction(-), Dot product,Cross product between two vectors. Also find angle between two vectors.

from math import *

class vector:
    def __init__(self, x, y, z):
        self.x = float(x)
        self.y = float(y)
        self.z = float(z)
    def dot(self, other):
        return self.x*other.x + self.y*other.y + self.z*other.z
    def cross(self, other):
        return vector(self.y*other.z-self.z*other.y, self.z*other.x-self.x*other.z, \
    def mod(self):
        return pow(self.x**2+self.y**2+self.z**2, 0.5)
    def __sub__(self, other):
        return vector(self.x-other.x, self.y-other.y, self.z-other.z)
    def __add__(self, other):
        return vector(self.x+other.x, self.y+other.y, self.z+other.z)
    def __str__(self, precision=2):
        return str(("%."+"%df"%precision)%float(self.x))+'i'+('+' if self.y>=0 else '-')+ \
                str(("%."+"%df"%precision)%float(abs(self.y)))+'j'+('+' if self.z>=0 else '-')+\
if __name__ == "__main__":
    print "Enter x,y,z(separeated by space) value of vector-1" 
    A = vector(*map(float, raw_input().strip().split()))
    print "Enter x,y,z(separeated by space) value of vector-2" 
    B = vector(*map(float, raw_input().strip().split()))
    print "A + B: " + str(A+B)
    print "A - B: " +str(A-B)
    print "A[.]B: " + str(
    print "A[X]B: " + str(A.cross(B))
    print "Modulas of A (|A|): " + str(A.mod())
    print "Modulas of B (|B|): "+ str(B.mod())
    print "Angle between then in radian is %.2f"%degrees(acos(*B.mod())))
Sample output:-
Enter x,y,z(separated by space) value of vector-1
2 4 -5
Enter x,y,z(separated by space) value of vector-2
-1 3 -2
A + B: 1.00i+7.00j-7.00k
A - B: 3.00i+1.00j-3.00k
A[.]B: 20.0
A[X]B: 7.00i+9.00j+10.00k
Modulas of A (|A|): 6.7082039325
Modulas of B (|B|): 3.74165738677
Angle between then in radian is 37.17

Here we have used operator overloading concept to add/subtract vectors. Refer this for another example of operator overloading in Python.In order to find radian value of angle between two vector used math.acos(x) which return the arc cosine of x, in radians.
Location: Hyderabad, Telangana, India