zoukankan      html  css  js  c++  java
  • yablog: calculate cosine with python numpy

    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


    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    import 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)
        print get_degrees_from_radian(radian)
     
    if __name__ == "__main__":
        main()
  • 相关阅读:
    第二阶段团队冲刺第二天站立会议
    第二阶段冲刺第一天站立会议
    对身边常用的软件进行评价
    学习进度条
    进度条
    团队冲刺第四天站立会议
    用户模板及场景分析
    团队冲刺第一天战略会议
    团队冲刺第九天
    团队冲刺第八天
  • 原文地址:https://www.cnblogs.com/lexus/p/2808450.html
Copyright © 2011-2022 走看看