Python 家庭作业:如何在不使用linalg.norm的情况下计算两个向量之间的距离?

Python 家庭作业:如何在不使用linalg.norm的情况下计算两个向量之间的距离?,python,distance,Python,Distance,如何在不使用linalg.norm的情况下,使用欧几里德距离公式写入两个向量之间的距离 这是我写的代码:(这很有效,我只是想知道如何用另一种方法来做……老师说这大约需要10-15行代码,但通过我的研究,这种方法似乎容易得多。(我想我就是不能使用linalg.norm。) import numpy as np def distance(arr1,arr2): dist = np.linalg.norm(arr1 - arr2) return dist 使用numpy.

如何在不使用linalg.norm的情况下,使用欧几里德距离公式写入两个向量之间的距离

这是我写的代码:(这很有效,我只是想知道如何用另一种方法来做……老师说这大约需要10-15行代码,但通过我的研究,这种方法似乎容易得多。(我想我就是不能使用linalg.norm。)

import numpy as np

def distance(arr1,arr2):    
    dist = np.linalg.norm(arr1 - arr2)

    return dist

使用
numpy.linalg.norm
更容易,因为您依赖于已经编写的函数

本练习的目的是提高您的编程和数学知识

从公式开始,编写一个函数来执行计算中的每个必要步骤

# Calculate the Euclidean distance between two points (P and Q)
def calculate_Euclidean_distance(point_P_list, point_Q_list):
    log.debug('Enter calculate_Euclidean_distance')
    log.info('point_P_list: (%s)' % ', '.join(map(str, point_P_list)))
    log.info('point_Q_list: (%s)' % ', '.join(map(str, point_Q_list)))

    # Store the sum of squared distances between coordinates
    sum_of_coordinate_distance_squared = 0
    # For each coordinate p and q in the points P and Q square the difference
    for p, q in zip(point_P_list, point_Q_list):
        distance_pq_squared = (p - q) ** 2
        sum_of_coordinate_distance_squared += distance_pq_squared

    # The distance between points P and Q is the square root of the sum of coordinate differences squared
    distance_PQ = math.sqrt(sum_of_coordinate_distance_squared)
    log.info('distance_PQ: ' + str(distance_PQ))

np.sum((arr1-arr2)**2)**0.5
。好吧,首先,作业中说你不应该使用
linalg.norm
,但这正是你在这里做的。可能是
[2019-09-27 15:03:33,257] [main] Start example.py execution
[2019-09-27 15:03:33,259] [calculate_Euclidean_distance] Enter calculate_Euclidean_distance
[2019-09-27 15:03:33,260] [calculate_Euclidean_distance] point_P_list: (9, 20)
[2019-09-27 15:03:33,261] [calculate_Euclidean_distance] point_Q_list: (18, 8)
[2019-09-27 15:03:33,261] [calculate_Euclidean_distance] distance_PQ: 15.0
[2019-09-27 15:03:33,261] [main] End example.py execution