math
Python 的 math
模块提供了许多数学运算的函数和常量,适用于浮点数的数学计算。以下是对 math
模块的详细介绍,包括其主要功能和常用方法。对于需要高精度或特殊数学功能的应用,可以结合使用 numpy
等其他库。
主要功能
常量
math.pi
: 圆周率 π 的值,约为 3.14159。math.e
: 自然对数的底数 e 的值,约为 2.71828。
python
import math
print(math.pi) # 输出 π
print(math.e) # 输出 e
1
2
3
4
2
3
4
数学函数
基本数学运算
math.sqrt(x)
: 返回 x 的平方根。math.pow(x, y)
: 返回 x 的 y 次幂。math.fabs(x)
: 返回 x 的绝对值(浮点数)。
pythonprint(math.sqrt(16)) # 输出 4.0 print(math.pow(2, 3)) # 输出 8.0 print(math.fabs(-5)) # 输出 5.0
1
2
3三角函数
math.sin(x)
: 返回 x(弧度)的正弦值。math.cos(x)
: 返回 x(弧度)的余弦值。math.tan(x)
: 返回 x(弧度)的正切值。math.asin(x)
,math.acos(x)
,math.atan(x)
: 返回反三角函数值。
pythonangle = math.pi / 4 # 45度 print(math.sin(angle)) # 输出 0.7071067811865475
1
2指数和对数
math.exp(x)
: 返回 e 的 x 次幂。math.log(x[, base])
: 返回 x 的自然对数(如果提供 base,则返回以 base 为底的对数)。math.log10(x)
: 返回 x 的以 10 为底的对数。
pythonprint(math.exp(1)) # 输出 e print(math.log(10)) # 输出 2.302585092994046 print(math.log10(100)) # 输出 2.0
1
2
3其他函数
math.factorial(x)
: 返回 x 的阶乘。math.gcd(x, y)
: 返回 x 和 y 的最大公约数。math.ceil(x)
: 返回大于或等于 x 的最小整数。math.floor(x)
: 返回小于或等于 x 的最大整数。
pythonprint(math.factorial(5)) # 输出 120 print(math.gcd(48, 18)) # 输出 6 print(math.ceil(4.2)) # 输出 5 print(math.floor(4.7)) # 输出 4
1
2
3
4整数平方根
math.isqrt(x)
: 返回 x 的整数平方根(Python 3.8+)。
pythonprint(math.isqrt(16)) # 输出 4
1
示例
计算圆的面积
可以使用 math
模块计算圆的面积。
python
def circle_area(radius):
return math.pi * radius ** 2
print(circle_area(5)) # 输出 78.53981633974483
1
2
3
4
2
3
4
解决三角形的边长
使用三角函数计算三角形的边长。
python
def triangle_side(opposite, angle):
return opposite / math.sin(math.radians(angle))
print(triangle_side(5, 30)) # 输出 10.0
1
2
3
4
2
3
4