python标准库math中计算平方根的函数_16 Python 标准库之 math 模块 - Python 进阶应用教程...

1. 前言

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

函数

功能

floor

向下取整

ceil

向上取整

pow

指数运算

fabs

绝对值

sqrt

开平方

modf

拆分小数和整数

fsum

计算列表中所有元素的累加和

copysign

复制符号

pi

圆周率

e

自然对数

2. math.floor(n)

函数 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

3. math.ceil(n)

函数 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

4. math.pow(n, m)

函数 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

5. math.fabs(n)

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

>>> import math

>>> math.fabs(1.23)

1.23

>>> math.fabs(-1.23)

1.23

6. math.sqrt(n)

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

>>> import math

>>> math.sqrt(4)

2.0

>>> math.sqrt(9)

3.0

>>> math.sqrt(16)

4.0

7. math.modf(n)

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

元组的第 0 项是小数

元组的第 1 项是整数

示例如下:

>>> import math

>>> math.modf(3.14)

(0.14, 3.0)

>>> tuple = math.modf(1949.1001)

>>> tuple[0]

0.1001

>>> tuple[1]

1949

在第 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([1, 2, 3])

6.0

>>> math.fsum((1, 2, 3)

6.0

在第 2 行,计算列表 [1, 2, 3] 中 3 个元素的累加和

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

9. math.copysign(a, b)

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

>>> import math

>>> math.copysign(2, -1)

-2.0

>>> math.copysign(-2, 1)

2.0

10. math.pi

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

>>> import math

>>> math.pi

3.141592653589793

11. math.e

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

>>> import math

>>> math.e

2.718281828459045

你可能感兴趣的:(python标准库math中计算平方根的函数_16 Python 标准库之 math 模块 - Python 进阶应用教程...)