[英]How to convert this numpy function to python math function?
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. 为了清楚起见,我不能使用 numpy package,所以我需要将其转换为仅使用 python 数学 ZEFE470A8E604A67F6D。 计算轨迹路径中的转折点枢轴点
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))))
仅使用数学 package 的解决方案:
输入
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:数组([0.92609311, 1.65565235, 0.61599073, 0.99699313, 0.73435661, 1.11279666])
仅使用数学 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]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.