I need to convert this function written using numpy to python math function, because of the limitation of what can be run on that python env. Just to be clear, I can't use numpy package, so I need to convert this to use python math package only. calculate-turning-points-pivot-points-in-trajectory-path
def angle(dir):
"""
Returns the angles between vectors.
Parameters:
dir is a 2D-array of shape (N,M) representing N vectors in M-dimensional space.
The return value is a 1D-array of values of shape (N-1,), with each value
between 0 and pi.
0 implies the vectors point in the same direction
pi/2 implies the vectors are orthogonal
pi implies the vectors point in opposite directions
"""
dir2 = dir[1:]
dir1 = dir[:-1]
return np.arccos((dir1*dir2).sum(axis=1)/(
np.sqrt((dir1**2).sum(axis=1)*(dir2**2).sum(axis=1))))
Solution using only math package:
Input
dir = [[3.6037027761255773, 0.03783693694249879],
[0.7663216820938965, 1.0418014197729653],
[-4.471037511834608, 2.7372078232282355],
[-1.621866618487419, -0.10824572436577373],
[-0.47906872408710144, -0.8621976119399739],
[0.5785645169182829, -2.50257598057014],
[1.4633910499042218, -0.34388406197396804]]
Numpy
dir2 = dir[1:]
dir1 = dir[:-1]
d1 = np.array(dir1)
d2 = np.array(dir2)
np.arccos((d1*d2).sum(axis=1)/(np.sqrt((d1**2).sum(axis=1)*(d2**2).sum(axis=1))))
Output: array([0.92609311, 1.65565235, 0.61599073, 0.99699313, 0.73435661, 1.11279666])
Using only math package
from math import sqrt, acos
def sum_elementwise(d):
return [x+y for x,y in d]
def multiply_elementwise(d1,d2):
return [[x*y for x, y in zip(a, b)]for a,b in zip(d1 ,d2)]
m1 = sum_elementwise(multiply_elementwise(dir1,dir1))
m2 = sum_elementwise(multiply_elementwise(dir2,dir2))
r1 = [a*b for a,b in zip(m1,m2)]
s1 = [sqrt(a) for a in r1]
e1 = sum_elementwise(multiply_elementwise(dir1,dir2))
x1 = [a/b for a,b in zip(e1,s1)]
result = [acos(a) for a in x1]
Output: [0.9260931132998823, 1.6556523484300858, 0.615990729086477, 0.9969931272447804, 0.7343566076471475, 1.112796657373265]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.