Python Math 模块

Python Math 模块

1. 前言

math 模块中包含了各种浮点运算函数,包括:

函数功能
floor向下取整
ceil向上取整
pow指数运算
fabs绝对值
sqrt开平方
modf拆分小数和整数
fsum计算列表中所有元素的累加和
copysign复制符号
pi圆周率
e自然对数

2. math.floor(n)

函数 math.floor(n) 的功能是对浮点数 n 向下取整,示例如下:

>>> import math>>> math.floor()>>> math.floor()>>> math.floor(-)->>> math.floor(-)-

3. math.ceil(n)

函数 math.ceil(n) 的功能是对浮点数 n 向上取整,示例如下:

>>> import math>>> math.ceil()>>> math.ceil()>>> math.ceil(-)->>> math.ceil(-)-

4. math.pow(n, m)

函数 math.pow(n, m) 的功能是指数运算,n 是底数,m 是指数,示例如下:

>>> import math>>> math.pow(, )>>> math.pow(, )>>> math.pow(, )>>> math.pow(, )>>> math.pow(, )

5. math.fabs(n)

函数 math.fabs(n) 的功能是计算 n 的绝对值,示例如下:

>>> import math>>> math.fabs()>>> math.fabs(-)

6. math.sqrt(n)

函数 math.sqrt(n) 的功能是计算 n 的平方根,示例如下:

>>> import math>>> math.sqrt()>>> math.sqrt()>>> math.sqrt()

7. math.modf(n)

函数 math.modf(n) 的功能是将浮点数 n 拆分为小数和整数,函数返回一个元组:

  • 元组的第 0 项是小数

  • 元组的第 1 项是整数

示例如下:

>>> import math>>> math.modf()(, )>>> tuple = math.modf()>>> tuple[]>>> tuple[]
  • 在第 3 行

    • 0.14 是 3.14 的小数部分

    • 3.0 是 3.14 的整数部分

  • 在第 6 行,0.1001 是 1949.1001 的小数部分

  • 在第 6 行,1949 是 1949.1001 的整数部分

8. math.fsum(list)

函数 math.fsum(list) 的功能是计算列表中所有元素的累加和,示例如下:

>>> import math>>> math.fsum([, , ])>>> math.fsum((, , )
  • 在第 2 行,计算列表 [1, 2, 3] 中 3 个元素的累加和

  • 在第 4 行,计算元组 (1, 2, 3) 中 3 个元素的累加和

9. math.copysign(a, b)

函数 math.copysign(a, b) 的功能是将参数 b 的正负符号复制给第一个数,示例如下:

>>> import math>>> math.copysign(, -)->>> math.copysign(-, )

10. math.pi

函数 math.pi 的功能是圆周率常量,示例如下:

>>> import math>>> math.pi

11. math.e

函数 math.e 的功能是自然对数常量,示例如下:

>>> import math>>> math.e