網站首頁 編程語言 正文
python如何取整
數據處理是編程中不可避免的,很多時候都需要根據需求把獲取到的數據進行處理,取整則是最基本的數據處理。
取整的方式則包括向下取整、四舍五入、向上取整等等。
1、向下取整
向下取整直接用內建的 int() 函數即可:
>>> a = 3.75
>>> int(a)
3
2、四舍五入
對數字進行四舍五入用 round() 函數:
>>> round(3.25); round(4.85)
3.0
5.0
3、向上取整
向上取整需要用到 math 模塊中的 ceil() 方法:
>>> import math
>>> math.ceil(3.25)
4.0
>>> math.ceil(3.75)
4.0
>>> math.ceil(4.85)
5.0
4、分別取整數部分和小數部分
有時候我們可能需要分別獲取整數部分和小數部分,這時可以用 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中的取整問題
雖然取整是各種語言中最基礎的操作, 可是往往多了一個1或者少了一個1會導致巨大的災難,所以我覺得還是很有必要寫一下的。
python中的取整操作有://, round, int, ceil, floor, 其他語言也有類似的函數來進行取整。
先看一段代碼
import math
def test_round(a, b):
? ? print('-------------------------------------')
? ? print(f'{a}/{b}=', a/b)
? ? print(f'{a}//{b}=', a//b)
? ? print(f'round({a}/{b})=', round(a/b))
? ? print(f'int({a}/{b})=', int(a/b))
? ? print(f'ceil({a}/{b})=', math.ceil(a/b))
? ? print(f'floor({a}/{b})=', math.floor(a/b))
test_round(3, 2)
test_round(-3, 2)
打印結果:
-------------------------------------
3/2= 1.5
3//2= 1
round(3/2)= 2
int(3/2)= 1
ceil(3/2)= 2
floor(3/2)= 1
-------------------------------------
-3/2= -1.5
-3//2= -2
round(-3/2)= -2
int(-3/2)= -1
ceil(-3/2)= -1
floor(-3/2)= -2
可以看出, //操作結果和floor是一樣的。
總的來說, ceil:坐標軸上向上取整, floor:向下取整, int:向中(0)取整(直接去掉浮點位)。
而round則是四舍五入(不考慮符號)
總結
原文鏈接:https://blog.csdn.net/m0_51713294/article/details/110632272
相關推薦
- 2022-12-25 Flutter桌面開發windows插件開發_Android
- 2022-12-02 Android?使用?okhttp3和retrofit2?進行單文件和多文件上傳_Android
- 2022-12-05 關于adfuller函數返回值的參數說明與記錄_python
- 2022-05-02 構建及部署jenkins?pipeline實現持續集成持續交付腳本_服務器其它
- 2024-01-08 Request請求轉發和Response重定向
- 2022-07-12 windows11下的dockerDesktop4.8.2資源目錄掛載
- 2022-06-28 EF?Core項目中不同數據庫需要的安裝包介紹_實用技巧
- 2022-04-03 Rust?連接?PostgreSQL?數據庫的詳細過程_PostgreSQL
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支