Python Code to Find out the Dot Product of Vectors and Angle between them (Using end Point Co-ordinates too)

Hi, 

Sometimes you are given with the endpoints’ co-ordinates of vectors, and sometimes you are directly given the vectors. For both conditions, the code given below will work. You have to input them as and when asked. End results will give the vectors, their magnitudes, their dot product and the angle between the two vectors. 

Python is a computer programming language that can be used to develip softwares, apps, and websites etc. The following python code provides a short solution to the Vector Algebra. 


Code: 


import numpy as np

import math

 a1 = input(‘For vector1, co-ordinates given? (y/n): ‘)

a2 = input('For vector2, co-ordinates given? (y/n): ')
u = input('unit: ')
if a1 == 'y':
x11= float(input('enter co-ordinates of starting point, x11= '))
y11 = float(input('y11= '))
z11 = float(input('z11 = '))
V11 = np.array([x11, y11, z11])

x21 = float( input('enter co-ordinates of end point, x21= '))
y21 = float(input('y21= '))
z21 = float(input('z21 = '))
V21 = np.array([x21, y21, z21])

print(f'Starting point, V11 = {V11}')
print(f'Ending point, V21 = {V21}')
v1 = V21 - V11
print(f'Vector1, V1 = V21 - V11 = {v1}')
v1m = np.sqrt((x21-x11) ** 2 + (y21-y11) ** 2 + (z21-z11) ** 2)
print(f" Magnitude of v1, v1m = {v1m} {u}")
else:
print('enter the elements in vector1 ')
x1 = float(input())
y1 = float(input())
z1 = float(input())
v1 = [x1,y1,z1]
print(f'v1 =({x1}i + {y1}j + {z1}k) {u}' 'n')
v1m = np.sqrt(x1**2 + y1**2 + z1**2)
print(f" Magnitude of v1, v1m = √(({x1})^2 + ({y1})^2 + ({z1})^2 = {v1m} {u}" 'n')

if a2 == 'y':
x12= float( input('enter co-ordinates of starting point, x21 = '))
y12 = float(input('y12= '))
z12 = float(input('z12 = '))
V12 = np.array([x12, y12, z12])

x22 = float( input('enter co-ordinates of end point, x22 = '))
y22 = float(input('y22= '))
z22 = float(input('z22 = '))
V22 = np.array([x22, y22, z22])
print(f'Starting point, V12 = {V12}')
print(f'Ending point, V22 = {V22}')
v2 = V22 - V12
print(f'Vector2, V2 = V22 - V12 = {v2}')
v2m = np.sqrt((x22 - x12) ** 2 + (y22 - y12) ** 2 + (z22 - z12) ** 2)
print(f" Magnitude of v2, v2m = {v2m} {u}")

else:
print('enter the elements in the 2nd vector: ')
x2 = float(input())
y2 = float(input())
z2 = float(input())
v2 = [x2,y2,z2]
print(f'v2 = ({x2}i + {y2}j + {z2}k) {u}' 'n')
v2m = np.sqrt(x2**2 + y2**2 + z2**2)
print(f" Magnitude of v2, v2m = √(({x2})^2 + ({y2})^2 + ({z2})^2 = {v2m} {u}" 'n')

d = float(np.dot(v1,v2))
e = d/(v1m*v2m)
a = math.acos(e)
k = math.degrees(a)

print(f'''Taking Dot product, v1.v2 = v1m * v2m * cosθ

=> cosθ = v1.v2/(v1m*v2m) = {d}/({v1m}*{v2m}) = {e}

hence, Angle between the two vectors, θ = acos({e}) = {k}
''')

Leave a Comment

Your email address will not be published. Required fields are marked *

PHP Code Snippets Powered By : XYZScripts.com