Python math.hypot() 方法



Python 的 math.hypot() 方法用於計算直角三角形的斜邊長度。

在 Python 3.8 之前的版本中,此方法僅用於查詢直角三角形的斜邊長度;但在 Python 3.8 及之後的版本中,它也用於查詢歐幾里得範數。

歐幾里得範數定義為笛卡爾平面上原點與座標之間的距離。因此,它實際上就是斜邊,其中座標軸充當直角三角形的底邊和高。

為了更好地理解這一點,讓我們來看下面的圖示 -

Number Hypot

注意 - 此函式不能直接訪問,因此我們需要匯入 math 模組,然後需要使用 math 靜態物件呼叫此函式。

語法

以下是 Python math.hypot() 方法的語法 -

math.hypot(x, y)

引數

  • x, y - 必須是數值。

返回值

此方法返回歐幾里得範數,sqrt(x*x + y*y)。

示例

以下示例演示了 Python math.hypot() 方法的用法。這裡,我們建立兩個包含正浮點值的數字物件。這些物件作為引數傳遞給此方法,並計算歐幾里得範數。

import math # This will import the math module

# Create two numeric objects
x = 12.98
y = 44.06

# Calculate the euclidean norm
hyp = math.hypot(x, y)

# Display the length of the euclidean norm
print("The length of Euclidean norm is:", hyp)

執行以上程式時,會產生以下結果 -

The length of Euclidean norm is: 45.93216737755797

示例

即使我們將負座標 x 和 y 作為引數傳遞給此方法,歐幾里得範數也會作為正值獲得(因為它是距離)。

在以下示例中,我們建立兩個包含負值的數字物件。這些物件作為引數傳遞給該方法,並計算歐幾里得範數的長度。

import math # This will import the math module

# Create two numeric objects with negative values
x = -10.66
y = -15.12

# Calculate the euclidean norm
hyp = math.hypot(x, y)

# Display the length of the euclidean norm
print("The length of Euclidean norm is:", hyp)

讓我們編譯並執行給定的程式,輸出如下 -

The length of Euclidean norm is: 18.5

示例

假設 x 和 y 座標分別作為正無窮大和負無窮大值傳遞,歐幾里得範數的長度將是正無窮大。

import math # This will import the math module

# Create two numeric objects with infinity
x = float("inf")
y = float("-inf")

# Calculate the Euclidean norm
hyp = math.hypot(x, y)

# Display the length of the Euclidean norm
print("The length of Euclidean norm is:", hyp)

執行上面的程式後,輸出如下 -

The length of Euclidean norm is: inf

示例

當我們將NaN值作為引數傳遞給此方法時,返回值也將是NaN值。

import math # This will import the math module

# Create two numeric objects with NaN values
x = float("nan")
y = float("nan")

# Calculate the euclidean norm
hyp = math.hypot(x, y)

# Display the length of the euclidean norm
print("The length of Euclidean norm is:", hyp)

編譯並執行程式,結果如下:

The length of Euclidean norm is: nan
python_maths.htm
廣告