1.函数名及其来源
这是math模块的一个函数 pow() 源于英文power,返回给定数字的乘幂 我们执行math.pow()示例:
>>>math.pow( 100, 2 )
10000.0
>>> math.pow(100,0.5)
10.0
特别注意:math 模块则会把参数转换为 float。
2.函数定义源码及其用法拆解
math是非常常用的数学计算包,其中math.pow()语法如下
import math
math.pow( x, y )
参数说明:
- x 幂函数的底
- y 幂函数的指数
等同于写法
x**y
但注意math函数返回的是浮点数,后者可能返回整数
>>>import math
>>>math.pow(2, 4)
16.0
>>>2**4
16
其他常用的数学函数有:
- abs(x)
>>>a = -10
>>>abs(a) # 注意不是math.abs
10 # 非math方法返回是整数
- math.fabs(x) 返回数字的绝对值,同abs()但这里是math的方法会转float
>>>import math
>>>math.fabs(-1)
1.0
- math.ceil(x) 返回数字的上入整数,如math.ceil(4.1) 返回 5
>>>import math
>>>a = 4.1
>>>math.ceil(a)
5
- math.floor(x) 返回数字的下舍整数
>>>import math
>>>a = 4.9
>>>math.floor(a)
4
- math.exp(x) 返回e的x次
>>>import math
>>>math.exp(1)
2.718281828459045
- math.log(x[,y]) 只传一个参数表示以e为底,传第二个y表示以y为底
>>>import math
>>>math.log(math.e)
1
>>>math.log(100,10)
2.0
- log10(x) 返回以10为底的x的对数
>>>import math
>>>math.log10(100)
2.0
- math.sqrt(x) 表示求x的平方根
>>>import math
>>>math.sqrt(100)
10.0
- max(x1, x2,...) 返回给定参数的最大值,参数可以为序列包括列表,集合和元组。
>>> max([1,2,3]) #列表
3
>>> max({1,2,3}) #集合
3
>>> max((1,2,3)) #元组
3
- min(x1, x2,...) 返回给定参数的最小值,参数可以为序列。
>>> min([7,8,9]) #列表
7
>>> min({7,8,9}) #集合
7
>>> min((7,8,9)) #元组
7
- math.modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
>>>import math
>>> math.modf(9.87)
(0.8699999999999992, 9.0)
>>> math.modf(-9.87)
(-0.8699999999999992, -9.0)
- round(x [,n])返回浮点数x的四舍五入值,如给出n值,则代表舍入到小数点后的位数。 注意不是math.round,这里五入必须大于5
>>> round(4.4999999)
4
>>> round(4.50000001)
5
>>> round(4.50000000)
4
>>> round(4.50000001,2)
4.5
>>> round(4.50000001,3)
4.5
3.版本差异
python2 有cmp(x,y)函数,python3移除了cmp,新增了 operator模块,提供了如下比较方法
- operator.gt(x,y) (greater than 大于)
- operator.ge(x,y) (greater equal 大于等于)
- operator.eq(x,y) (equal 等于)
- operator.le(x,y) (less equal 小于等于)
- operator.lt(x,y) (less than 小于)
作为比较函数
4.学习建议
在处理数字时使用数学函数能更高效的获取计算结果。
对基础运行环境有疑问的,推荐参考:python函数深入浅出 0.基础篇