網(wǎng)站首頁 編程語言 正文
python如何取整
數(shù)據(jù)處理是編程中不可避免的,很多時候都需要根據(jù)需求把獲取到的數(shù)據(jù)進行處理,取整則是最基本的數(shù)據(jù)處理。
取整的方式則包括向下取整、四舍五入、向上取整等等。
1、向下取整
向下取整直接用內建的 int() 函數(shù)即可:
>>> a = 3.75
>>> int(a)
3
2、四舍五入
對數(shù)字進行四舍五入用 round() 函數(shù):
>>> 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、分別取整數(shù)部分和小數(shù)部分
有時候我們可能需要分別獲取整數(shù)部分和小數(shù)部分,這時可以用 math 模塊中的 modf() 方法,該方法返回一個包含小數(shù)部分和整數(shù)部分的元組:
>>> 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) 才對。
這里涉及到了另一個問題,即浮點數(shù)在計算機中的表示,在計算機中是無法精確的表示小數(shù)的,至少目前的計算機做不到這一點。
上例中最后的輸出結果只是 0.2 在計算中的近似表示。
python中的取整問題
雖然取整是各種語言中最基礎的操作, 可是往往多了一個1或者少了一個1會導致巨大的災難,所以我覺得還是很有必要寫一下的。
python中的取整操作有://, round, int, ceil, floor, 其他語言也有類似的函數(shù)來進行取整。
先看一段代碼
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
相關推薦
- 2023-07-18 讀取Springboot的jar包中的文件資源方式
- 2022-10-05 C語言二叉樹的概念結構詳解_C 語言
- 2022-08-03 C++編程語言中賦值運算符重載函數(shù)(operator=)的使用_C 語言
- 2022-08-21 HTTP協(xié)議詳細介紹_其它綜合
- 2022-03-29 詳解C++?的STL迭代器原理和實現(xiàn)_C 語言
- 2022-06-11 C#把EXCEL數(shù)據(jù)轉換成DataTable_C#教程
- 2022-02-24 Go入門所踩過的坑:cannot find package "" in any of
- 2021-12-02 golang配制高性能sql.DB的使用_Golang
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支