Python三角学

示例

计算斜边的长度

math.hypot(2, 4) # 只是SquareRoot(2 ** 2 + 4 ** 2)的简写
# 出:4.47213595499958

将角度转换为弧度

所有math函数都期望弧度,因此您需要将度数转换为弧度:

math.radians(45)              # 转换45度为弧度
# 出:0.7853981633974483

逆三角函数的所有结果以弧度形式返回结果,因此您可能需要将其转换回度:

math.degrees(math.asin(1))    # 将asin的结果转换为度
# 出局:90.0

正弦,余弦,正切和反函数

# 正弦和反正弦
math.sin(math.pi / 2)
# 出:1.0
math.sin(math.radians(90))   # 90度正弦
# 出:1.0

math.asin(1)
# Out: 1.5707963267948966    # "= pi / 2"
math.asin(1) / math.pi
# 出:0.5

# 余弦和反余弦:
math.cos(math.pi / 2)
# 出:6.123233995736766e-17 
# Almost zero but not exactly because "pi" is a float with limited precision!

math.acos(1)
# 出:0.0

# 切线和反正切:
math.tan(math.pi/2)
# 出:1.633123935319537e + 16 
# Very large but not exactly "Inf" because "pi" is a float with limited precision

Python 3.x 3.5
math.atan(math.inf)
# Out: 1.5707963267948966 # This is just "pi / 2"

math.atan(float('inf'))
# Out: 1.5707963267948966 # This is just "pi / 2"

除了之外,math.atan还有两个参数的math.atan2函数,该函数计算正确的象限并避免被零除的陷阱:

math.atan2(1, 2)   # Equivalent to "math.atan(1/2)"
# Out: 0.4636476090008061 # ≈26.57度,第一象限

math.atan2(-1, -2) # Not equal to "math.atan(-1/-2)" == "math.atan(1/2)"
# Out: -2.677945044588987 # ≈-153.43度(或206.57度),第三象限

math.atan2(1, 0)   # math.atan(1/0)将引发ZeroDivisionError
# Out: 1.5707963267948966 # This is just "pi / 2"

双曲正弦,余弦和正切

# 双曲正弦函数
math.sinh(math.pi) # = 11.548739357257746
math.asinh(1)      # = 0.8813735870195429

# 双曲余弦函数
math.cosh(math.pi) # = 11.591953275521519
math.acosh(1)      # = 0.0

# 双曲正切函数
math.tanh(math.pi) # = 0.99627207622075
math.atanh(0.5)    # = 0.5493061443340549