給定直角三角形的兩條直角邊,用Python返回它的斜邊。


要獲得斜邊,請在Python NumPy中使用numpy.hypot()方法。該方法返回三角形(s)的斜邊。如果x1和x2都是標量,則這是一個標量。此方法等效於sqrt(x1**2 + x2**2),逐元素計算。如果x1或x2是標量型別,則將其廣播以用於另一個引數的每個元素。引數是三角形(s)的直角邊。如果x1.shape != x2.shape,則它們必須可以廣播到公共形狀。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個包含整數元素的陣列:

arr = np.ones((3, 3), dtype=int)

顯示我們的陣列:

print("Array...\n",arr)

獲取資料型別:

print("\nArray datatype...\n",arr.dtype)

獲取陣列的維度:

print("\nArray Dimensions...\n",arr.ndim)

獲取陣列的元素個數:

print("\nNumber of elements in the Array...\n",arr.size)

獲取斜邊:

print("\nHypotenuse..\n",np.hypot((3*arr), (4*arr)))

示例

import numpy as np

# To get the hypotenuse, use the numpy.hypot() method in Python Numpy.
# The method returns the hypotenuse of the triangle(s). This is a scalar if both x1 and x2 are scalars.
# This method is equivalent to sqrt(x1**2 + x2**2), element-wise. If x1 or x2 is scalar_like, it is broadcast for use with each element of the other argument.
# The parameters are the leg of the triangle(s). If x1.shape != x2.shape, they must be broadcastable to a common shape.

# Creating an array with integer elements
arr = np.ones((3, 3), dtype=int)

# Display the array
print("Array...\n", arr)

# Get the type of the array
print("\nOur Array type...\n", arr.dtype)

# Get the dimensions of the Array
print("\nOur Array Dimensions...\n",arr.ndim)

# Get the number of elements in the Array
print("\nNumber of elements...\n", arr.size)

# Get the hypotenuse
print("\nHypotenuse..\n",np.hypot((3*arr), (4*arr)))

輸出

Array...
[[1 1 1]
[1 1 1]
[1 1 1]]

Our Array type...
int64

Our Array Dimensions...
2

Number of elements...
9

Hypotenuse..
[[5. 5. 5.]
[5. 5. 5.]
[5. 5. 5.]]

更新於:2022年2月28日

384次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告