python 功能函数

python 有5个运算内建函数用于数值运算:abs(),coerce(),divmod(),pow()和round()。


abs() 返回给定参数的绝对值。如果参数是一个复数,那么就返回 math.sqrt(num.real2 +num.imag2)

>>> abs(-1)
1
>>> abs(10.)
10.0
>>> abs(1.2-2.1j)
2.4186773244895647
>>> abs(0.23-0.78)
0.55

coerce() 仅返回一个包含类型转换完毕的两个数值元素的元组。

>>> coerce(1,2)
(1, 2)
>>> coerce(1.3 ,134l)
(1.3, 134.0)
>>> coerce(1,134l)
(1L, 134L)
>>> coerce(1j,134l)
(1j, (134+0j))
>>> coerce(1.23-41j,134l)
((1.23-41j), (134+0j))

divmod() 内建函数把除法和取余运算结合起来,返回一个包含商和余数的元组。

>>> divmod(10,3)
(3, 1)
>>> divmod(3,10)
(0, 3)
>>> divmod(10,2.5)
(4.0, 0.0)
>>> divmod(2.5,10)
(0.0, 2.5)
>>> divmod(2+1j,0.5-1j)
((-0+0j), (2+1j))

pow() 和双星号 (**) 操作符号都可以进行指数运算。

>>> pow(2,5)
32
>>> pow(5,2)
25
>>> pow(3.1415926,2)
9.86960406437476
>>> pow(1+1j,3)
(-2+2j)

round() 用于对浮点型进行四舍五入运算。它有一个可选的小数位数参数。如果不提供小数位参数,他返回与第一个参数最接近的整形(但仍然是浮点类型)。第二个参数告诉round函数将结果精确到小数点后指定位数。

>>> round(3)
3.0
>>> round(3.45)
3.0
>>> round(3.499999999)
3.0
>>> round(3.499999999,1)
3.5
>>> import math
>>> for eachNum in range(10):
...     print round(math.pi,eachNum)
... 
3.0
3.1
3.14
3.142
3.1416
3.14159
3.141593
3.1415927
3.14159265
3.141592654
>>> round(-3.5)
-4.0
>>> round(-3.4)
-3.0
>>> round(-3.49)
-3.0
>>> round(-3.49,1)
-3.5

round() 函数是按四舍五入的规则进行取整的。

int() ,round(),math.floor() 它们之间的不同之处。

函数int() 直接截去小数部分(返回值为整形)。

函数floor()得到最接近原数但小于原数的整形(返回值为浮点型)。

函数round()得到最接近原数的整形(返回值为浮点型)。

>>> import math
>>> for eachNum in (.2,.7,1.2,1.7,-.2,-.7,-1.2,-1.7):
...       print"int(%.1f)\t%+.1f" % (eachNum,float(int(eachNum)))
...       print"floor(%.1f)\t%+.1f"%(eachNum,math.floor(eachNum))
...       print"round(%.1f)\t%+.1f"%(eachNum,round(eachNum))
...       print'-' * 20
... 
int(0.2)	+0.0
floor(0.2)	+0.0
round(0.2)	+0.0
--------------------
int(0.7)	+0.0
floor(0.7)	+0.0
round(0.7)	+1.0
--------------------
int(1.2)	+1.0
floor(1.2)	+1.0
round(1.2)	+1.0
--------------------
int(1.7)	+1.0
floor(1.7)	+1.0
round(1.7)	+2.0
--------------------
int(-0.2)	+0.0
floor(-0.2)	-1.0
round(-0.2)	-0.0
--------------------
int(-0.7)	+0.0
floor(-0.7)	-1.0
round(-0.7)	-1.0
--------------------
int(-1.2)	-1.0
floor(-1.2)	-2.0
round(-1.2)	-1.0
--------------------
int(-1.7)	-1.0
floor(-1.7)	-2.0
round(-1.7)	-2.0
--------------------



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值