Last active
December 27, 2015 19:29
-
-
Save mstaflex/7377211 to your computer and use it in GitHub Desktop.
Vektor operations (basic) in python - always need it - always reprogram it - until now ;)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import math | |
from math import sin, cos, pi | |
from numpy import dot, matrix, array | |
from numpy.linalg import norm | |
#import numpy as np | |
# author Jasper Buesch | |
def rotate_vector(angle=0, vector=(0,0)): | |
rot_mat = matrix( ((cos(angle),-sin(angle)), (sin(angle), cos(angle))) ) | |
vector = array(vector) | |
result = vector * rot_mat | |
return result.tolist()[0] | |
def sub_vectors(a, b): | |
"""Subtracts b from a. | |
E.g. if the vector pointing from b to a is to be calculated. sub_vectors(a, b)""" | |
diff = array(a) - array(b) | |
return diff.tolist() | |
def angle_between(a,b): | |
"""Returns the angle between two vectors - a is the reference. | |
The return value lies between 0 an pi.""" | |
na, nb = norm(a), norm(b) | |
assert na > 0 and nb > 0 | |
arccosInput = dot(a,b)/na/nb | |
arccosInput = 1.0 if arccosInput > 1.0 else arccosInput | |
arccosInput = -1.0 if arccosInput < -1.0 else arccosInput | |
return math.acos(arccosInput) | |
def angle_between_s(a, b): | |
"""Returns the angle between a and b. a is the reference. | |
If the angle is between 0 and pi in math-positive direction | |
and between 0 and -pi in the clockwise direction.""" | |
angle = angle_between(a,b) | |
if angle < angle_between(a, rotate_vector(angle=0.001, vector=b)): | |
return - angle | |
else: | |
return angle | |
if __name__ == "__main__": | |
print "subtracting b=(1, 1) from a=(2, 1): ", sub_vectors( (2,1), (1,1)) | |
print "###" | |
print "angle_between_s( (0,1), (1,0) ): ", angle_between_s( (0,1), (1,0) ) # math negative | |
print "angle_between_s( (1,0), (0,1) ): ", angle_between_s( (1,0), (0,1) ) # math positive | |
print "###" | |
print "(1,0) rotated by 90 degrees in math pos dir: ", rotate_vector(angle=pi/2, vector=(1,0)) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment