Advertisement
jukaukor

vectors.py

Feb 11th, 2019
145
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. # Vectors in Python without numpy
  2. # juhani Kaukoranta
  3. # 11.2.2019
  4.  
  5. from math import sqrt, acos, degrees
  6. from operator import mul
  7.  
  8. def dotproduct(a,b):
  9. return sum(map(mul,a,b))
  10. def norm(a):
  11. # norm, length of vector a
  12. return sqrt(dotproduct(a,a))
  13.  
  14. def anglerad(a,b):
  15. # angle between vectors a and b in radians
  16. return acos(dotproduct(a,b)/norm(a)/norm(b))
  17.  
  18. def angledeg(a,b):
  19. # angle between vectors a and b in radians
  20. return degrees(anglerad(a,b))
  21.  
  22. def crossproduct(a,b):
  23. assert len(a) == len(b) == 3, 'Only 3D vectors, set missing component to 0'
  24. a1,a2,a3 = a
  25. b1,b2,b3 = b
  26. return [a2*b3 - a3*b2, a3*b1 - a1*b3, a1*b2 - a2*b1]
  27.  
  28. print("for example input vector [-3,5,4] are inputed : -3 5 4")
  29. # vector1
  30. input_vector = input("Enter first vector's components separated by space ")
  31. # muutetaan listan merkkijonokomponentit liukuluvuiksi
  32. vector1 = [float(i) for i in input_vector.split()]
  33. print("vector1 = ",vector1)
  34. # vector2
  35. input_vector = input("Enter second vector's components separated by space ")
  36. vector2 = [float(i) for i in input_vector.split()]
  37. print("vector2 = ",vector2)
  38. # dot product, norm, angle, cross product
  39. print("dotproduct of vectors = ",dotproduct(vector1,vector2))
  40. print("norm, length of vector1 = ",norm(vector1))
  41. print("norm, length of vector2 = ",norm(vector2))
  42. print("angle between vectors in radians = ",anglerad(vector1,vector2))
  43. print("angle between vectors in degrees = ",angledeg(vector1,vector2))
  44. print("cross product of vectors = ",crossproduct(vector1,vector2))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement