math 模块中包含了各种浮点运算函数,包括:
函数 | 功能 |
---|---|
floor | 向下取整 |
ceil | 向上取整 |
pow | 指数运算 |
fabs | 绝对值 |
sqrt | 开平方 |
modf | 拆分小数和整数 |
fsum | 计算列表中所有元素的累加和 |
copysign | 复制符号 |
pi | 圆周率 |
e | 自然对数 |
函数 math.floor(n) 的功能是对浮点数 n 向下取整,示例如下:
>>> import math
>>> math.floor(1.5)
1
>>> math.floor(2.5)
2
>>> math.floor(-1.5)
-2
>>> math.floor(-2.5)
-3
函数 math.ceil(n) 的功能是对浮点数 n 向上取整,示例如下:
>>> import math
>>> math.ceil(1.5)
2
>>> math.ceil(2.5)
3
>>> math.ceil(-1.5)
-1
>>> math.ceil(-2.5)
-2
函数 math.pow(n, m) 的功能是指数运算,n 是底数,m 是指数,示例如下:
>>> import math
>>> math.pow(2, 0)
1.0
>>> math.pow(2, 1)
2.0
>>> math.pow(2, 2)
4.0
>>> math.pow(2, 3)
8.0
>>> math.pow(2, 4)
16.0
函数 math.fabs(n) 的功能是计算 n 的绝对值,示例如下:
>>> import math
>>> math.fabs(1.23)
1.23
>>> math.fabs(-1.23)
1.23
函数 math.sqrt(n) 的功能是计算 n 的平方根,示例如下:
>>> import math
>>> math.sqrt(4)
2.0
>>> math.sqrt(9)
3.0
>>> math.sqrt(16)
4.0
函数 math.modf(n) 的功能是将浮点数 n 拆分为小数和整数,函数返回一个元组:
示例如下:
>>> import math
>>> math.modf(3.14)
(0.14, 3.0)
>>> tuple = math.modf(1949.1001)
>>> tuple[0]
0.1001
>>> tuple[1]
1949
函数 math.fsum(list) 的功能是计算列表中所有元素的累加和,示例如下:
>>> import math
>>> math.fsum([1, 2, 3])
6.0
>>> math.fsum((1, 2, 3)
6.0
函数 math.copysign(a, b) 的功能是将参数 b 的正负符号复制给第一个数,示例如下:
>>> import math
>>> math.copysign(2, -1)
-2.0
>>> math.copysign(-2, 1)
2.0
函数 math.pi 的功能是圆周率常量,示例如下:
>>> import math
>>> math.pi
3.141592653589793
函数 math.e 的功能是自然对数常量,示例如下:
>>> import math
>>> math.e
2.718281828459045