Python math.hypot()方法

Pythonmath.hypot() 方法用于计算任何输入坐标值的欧几里得准则。欧几里得规范是原点和指定坐标之间的距离。

这个方法使用公式sqrt(x*x + y*y) 来计算答案。

语法

math.hypot(p, b)

参数

p 一个正数或负数代表一个直角三角形的垂直边。
b 一个正数或负数代表一个直角三角形的底边。

返回值

math.hypot() ,返回一个代表欧氏规范的浮点值、sqrt(x*x + y*y).

示例代码

让我们通过下面不同的代码例子来学习math.hypot() 方法的使用。

使用math.hypot() ,有两个输入值

示例代码:

import math
p = 6
b= 4
value= math.hypot(p,b)
print(f"The hypotenuse of a right-angle triangle having the perpendicular {p} and base {b} is {value}.")
p = -10
b = -2
value= math.hypot(p,b)
print(f"The hypotenuse of a right-angle triangle having the perpendicular {p} and base {b} is {value}.")
p = 0
b = 0
value= math.hypot(p,b)
print(f"The hypotenuse of a right-angle triangle having the perpendicular {p} and base {b} is {value}.")
p = math.inf
b = math.inf
value= math.hypot(p,b)
print(f"The hypotenuse of a right-angle triangle having the perpendicular {p} and base {b} is {value}.")

输出:

The hypotenuse of a right-angle triangle having the perpendicular 6 and base 4 is 7.211102550927979.
The hypotenuse of a right-angle triangle having the perpendicular -10 and base -2 is 10.19803902718557.
The hypotenuse of a right-angle triangle having the perpendicular 0 and base 0 is 0.0.
The hypotenuse of a right-angle triangle having the perpendicular inf and base inf is inf.

请注意,函数中输入的数值可以用来计算任何三角形的斜边。

使用math.hypot() ,有N个维度的点

示例代码:

import math
print(math.hypot(6, 9, 12))
print(math.hypot(9, 2, 11, 13))
print(math.hypot(10, 0, 3, 16, 23))

输出:

16.15549442140351
19.364916731037084
29.899832775452108

注意,新版本的Python支持在math.hypot() 中输入多个参数。

我们可以输入N维的点,然后返回从原点到指定坐标的矢量长度。

使用math.hypot() 与公式math.sqrt((p*p)+(b*b))

示例代码:

import math
p = 6
b= 4
value= math.sqrt((p*p)+(b*b))
print(f"The hypotenuse of a right-angle triangle having the perpendicular {p} and base {b} is {value}")

输出:

The hypotenuse of a right-angle triangle having the perpendicular 6 and base 4 is 7.211102550927978.

请注意,上述公式是math.hypot() 方法的基础工作。

查找math.hypot() 方法的时间复杂度

示例代码:

import math
import math
import time
p = 3
b = 8
startHypot = time.time()
hypot = math.hypot(p,b)
print("The hypotenuse of the right-angle triangle using the formula is "
       + str(hypot) + ".")
print("The time taken to compute the value using the formula is "
       + str(time.time() - startHypot) + ".")
start = time.time()
hypo = math.sqrt((p*p)+(b*b))
print("The hypotenuse of the right-angle triangle using the equation is "
       + str(hypo) + ".")
print("The time taken to compute the value using the equation is "
       + str(time.time() - start) + ".")

输出:

The hypotenuse of the right-angle triangle using the formula is 8.54400374531753.
The time taken to compute the value using the formula is 2.9325485229492188e-05.
The hypotenuse of the right-angle triangle using the equation is 8.54400374531753.
The time taken to compute the value using the equation is 5.4836273193359375e-06.

上面的代码使用time() 函数来确定math.hypot() 函数及其基础方程的时间复杂度。

事实证明,方程函数的计算速度更快,但在不同的平台上构建的结果可能不同。