hypot()
函数根据代表直角三角形两直角边的两个数组,计算斜边长度。斜边是直角三角形最长的一条边,位于直角对面。
示例
import numpy as np
# create two arrays representing the perpendicular sides of right triangles
x1 = np.array([3, 4, 5])
x2 = np.array([4, 12, 13])
# calculate the hypotenuse using numpy.hypot()
result = np.hypot(x1, x2)
print(result)
# Output : [ 5. 13. 13.]
hypot() 语法
hypot()
的语法是
numpy.round(x1, x2, out = None, where = True)
hypot() 参数
hypot()
函数接受一个参数
x1
- 第一个输入数组,包含直角三角形一条边的值x2
- 第二个输入数组,包含直角三角形另一条边的值out
(可选) - 用于存储结果的输出数组where
(可选) - 指定计算斜边长度的条件
hypot() 返回值
hypot()
函数返回一个新的数组,其中包含来自两个输入数组对应元素平方和的平方根的元素级结果。
示例 1:计算斜边长度
import numpy as np
# create two 1D arrays representing the perpendicular sides of right triangles
side1 = np.array([4, 5, 8])
side2 = np.array([3, 12, 15])
# calculate the hypotenuse lengths using numpy.hypot()
hypotenuse_lengths = np.hypot(side1, side2)
print("Hypotenuse lengths:")
print(hypotenuse_lengths)
输出
Hypotenuse lengths: [ 5. 13. 17.]
在此示例中,我们有两个一维数组 side1 和 side2,它们代表直角三角形的直角边。
np.hypot()
函数计算 side1 和 side2 中每一对对应元素的斜边长度。
数学上,
numpy.hypot(4, 3) = sqrt((4^2) + (3^2)) = sqrt(16 + 9) = sqrt(25) = 5
此计算代表 side1 和 side2 中第一对元素 (4, 3) 的斜边长度。
所有其余的对都以相同的方式计算。
示例 2:在 hypot() 中使用可选的 out 和 where 参数
import numpy as np
# create two arrays representing the perpendicular sides of right triangles
side1 = np.array([4, 5, 8])
side2 = np.array([3, 12, 15])
# create an empty array to store the hypotenuse lengths
result = np.zeros_like(side1, dtype=float)
# calculate the hypotenuse lengths using numpy.hypot() and
# store the results in the 'result' array
np.hypot(side1, side2, out=result, where=(side1 > 4))
print("Hypotenuse lengths:")
print(result)
输出
Hypotenuse lengths: [ 0. 13. 17.]
这里,
out=result
指定np.hypot()
函数的输出应存储在 result 数组中。where=(side1 > 4)
指定斜边长度的计算将仅对 side1 中大于 4 的元素进行。