1. 程式人生 > Python進階應用教學 >16 Python 標準庫之 math 模組

16 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(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