yablog: calculate cosine with python numpy
calculate cosine with python numpy
purpose
Calculate “cosine” determined by pair of vectors using python and its package named numpy. Firstly I show you the definition of cosine in linear space, and Secondly I share sample python code for calculating cosine.
definition of cosine in linear space
python code for calculating cosine
123456789101112131415161718192021222324252627282930313233import
numpy
def
get_cosine(v1, v2):
""" calculate cosine and returns cosine """
n1
=
get_norm_of_vector(v1)
n2
=
get_norm_of_vector(v2)
ip
=
get_inner_product(v1, v2)
return
ip
/
(n1
*
n2)
def
get_inner_product(v1, v2):
""" calculate inner product """
return
numpy.dot(v1, v2)
def
get_norm_of_vector(v):
""" calculate norm of vector """
return
numpy.linalg.norm(v)
def
get_radian_from_cosine(cos):
return
numpy.arccos(cos)
def
get_degrees_from_radian(cos):
return
numpy.degrees(cos)
def
main():
v1
=
numpy.array([
1
,
0
])
v2
=
numpy.array([
1
, numpy.sqrt(
3
)])
cosine
=
get_cosine(v1, v2)
radian
=
get_radian_from_cosine(cosine)
get_degrees_from_radian(radian)
if
__name__
=
=
"__main__"
:
main()
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/110267.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...