用Python计算两个向量之间的夹角余弦值

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

向量夹角的余弦公式很简单,不在此赘述,直接上代码:
def cosVector(x,y):
    if(len(x)!=len(y)):
        print('error input,x and y is not in the same space')
        return;
    result1=0.0;
    result2=0.0;
    result3=0.0;
    for i in range(len(x)):
        result1+=x[i]*y[i]   #sum(X*Y)
        result2+=x[i]**2     #sum(X*X)
        result3+=y[i]**2     #sum(Y*Y)
    #print(result1)
    #print(result2)
    #print(result3)
    print("result is "+str(result1/((result2*result3)**0.5))) #结果显示
cosVector([2,1],[1,1])

转载于:https://my.oschina.net/u/170911/blog/124787

你可能感兴趣的:(用Python计算两个向量之间的夹角余弦值)