python 常見的取整方法

2021-10-02 15:46:31 字數 1164 閱讀 6274

碎玉長青關注

2018.07.16 15:45:50字數 400閱讀 6,122

摘自 

資料處理是程式設計中不可避免的,很多時候都需要根據需求把獲取到的資料進行處理,取整則是最基本的資料處理。取整的方式則包括向下取整、四捨五入、向上取整等等。

向下取整直接用內建的int()函式即可:

>>> a = 3.75

>>> int(a)

3

對數字進行四捨五入用round()函式:

>>> round(3.25); round(4.85)

3.05.0

向上取整需要用到math模組中的ceil()方法:

>>> import math

>>> math.ceil(3.25)

4.0>>> math.ceil(3.75)

4.0>>> math.ceil(4.85)

5.0

有時候我們可能需要分別獲取整數部分和小數部分,這時可以用math模組中的modf()方法,該方法返回乙個包含小數部分和整數部分的元組:

>>> import math

>>> math.modf(3.25)

(0.25, 3.0)

>>> math.modf(3.75)

(0.75, 3.0)

>>> math.modf(4.2)

(0.20000000000000018, 4.0)

有人可能會對最後乙個輸出結果感到詫異,按理說它應該返回(0.2, 4.0)才對。這裡涉及到了另乙個問題,即浮點數在計算機中的表示,在計算機中是無法精確的表示小數的,至少目前的計算機做不到這一點。上例中最後的輸出結果只是 0.2 在計算中的近似表示。python 和 c 一樣, 採用ieee 754規範來儲存浮點數,如果希望更詳細的了解這一點,可以參考知乎話題: 為什麼0.1+0.2=0.30000000000000004而1.1+2.2=3.3000000000000003?.

python取整方法

用 math 模組中的 ceil 方法 import math math.ceil 3.25 4.0 math.ceil 3.75 4.0 math.ceil 4.85 5.0直接用內建的 int 函式即可 a 3.75 int a 3floor import math math.floor x 對...

Python取整的方法

python自帶的int 取整 int 1.2 1 int 2.8 2 int 0.1 0 int 5.6 5總結 int 函式是 向0取整 取整方向總是讓結果比小數的絕對值更小 import math math.ceil 0.6 1 math.ceil 1.1 2 math.ceil 3.0 3 ...

python 資料取整方法

參考 參考 向下取整 int math.floor a 12.66 int a 12 math.floor 3.14 3 math.floor 3.54 3向上取整 math.ceil import math math.ceil 3.14 4 math.ceil 3.66 4四捨五入 round r...