Làm thế nào để tính norm Euclidean trong Python?


Trong Python, chúng ta có thể tính norm Euclidean bằng cách sử dụng module numpy hoặc tính toán thủ công.

Sử dụng module numpy:

Để tính norm Euclidean bằng module numpy, chúng ta có thể sử dụng hàm numpy.linalg.norm() như sau:

import numpy as np

vector = np.array([3, 4, 5])
norm = np.linalg.norm(vector)

print(norm)

Kết quả sẽ là:

7.0710678118654755

Tính toán thủ công:

Nếu không muốn sử dụng module numpy, chúng ta có thể tính norm Euclidean bằng cách tính căn bậc hai của tổng bình phương các phần tử trong vector như sau:

import math

vector = [3, 4, 5]
norm = math.sqrt(sum(i**2 for i in vector))

print(norm)

Kết quả sẽ là:

7.0710678118654755


About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.