Python的数字函数

Math数字使用

import math;# 导入包,用math.调用

常见的数学函数:

函数名 描述
abs(x) 返回数字的绝对值,例abs(-1) 结果为 1
math.fabs(x) 返回数字的绝对值为float类型,例math.fabs(-1) 结果为 1.0
math.ceil(x) 向上取整,例math.ceil(1.2) 结果为 2
math.floor(x) 向下取整,例math.floor(1.9) 结果为 1
round(x, n) 返回浮点数x的四舍五入值,给出n,则舍入小数点后的位数,例round(4.5) 结果为 4,round(4.6)的结果为5
exp(x) 返回e的x次幂(ex),如math.exp(1) 返回2.718281828459045
log(x) 如math.log(math.e)返回1.0,math.log(100,10)返回2.0
log10(x) 返回以10为基数的x的对数,如math.log10(100)返回 2.0
max(x1, x2,…) 返回给定参数的最大值,参数可以为序列。
min(x1, x2,…) 返回给定参数的最小值,参数可以为序列。
modf(x) 返回x的整数部分与小数部分,两部分的数值符号与x相同,整数部分以浮点型表示。
pow(x, y) x**y 运算后的值。
sqrt(x) 返回数字x的平方根
cmp(x, y) Py2,如果 x < y 返回 -1, 如果 x == y 返回 0, 如果 x > y 返回 1
>>> import math
>>> abs(-1)
1
>>> math.fabs(-5)
5.0
>>> math.ceil(4.1)
5
>>> math.floor(5.9)
5
>>> round(4.6)
5
>>> round(4.2)
4
>>> pow(2,2)
4
# 用math调用pow()返回float类型的数据
>>> math.pow(2,3)
8.0

cmp()函数

python2使用,python3已取消

1.导入包 import operator

2.用operator.调用

判断 描述
eq(a, b) 判断两个值是否相等
lt(a, b) a是否小于b,相当于a < b
le(a, b) 相当于a <= b
ne(a, b) a不等于b时,返回True 相当于a != b
gt(a, b) a大于b时,返回True 相当于a > b
ge(a, b) a大于等于b时,返回True 相当于 a >= b

函数的返回值是布尔。

>>> import operator
>>> operator.eq('a', chr(97))
True
>>> operator.lt(1, 2);
True
>>> operator.le(1, 2);
True
>>> operator.ne(1,2)
True
>>> operator.gt(5,4);
True
>>> operator.ge(3,2);
True

随机数(random)

导入:import random;

1.random.random():0~1的随机数,返回浮点数

2.random.randint(x, y):返回x~y的随机整数,包尾

3.random.randrange(x, y, step):返回x~y的随机数,不包尾,有步长step没什么用

4.random.uniform(x, y):返回x~y的随机【浮点数】

5.random.choice( arr ):从列表、数组、元组中随机选取一个元素

6.random.shuffle( arr ):将列表、数组、元组中的顺序打乱。

7.random.sample(arr, n):从列表、数组、元组中随机获取 n 个元素。

>>> import random
>>> random.random()
0.5351776000910692
>>> random.randint(1,5)
1
>>> random.randrange(2,5)
4
>>> random.uniform(1,6)
4.000485875275471
>>> random.choice(["张三","杨过","小龙女","郭靖"])
'张三'
>>> random.sample(["张三","杨过","小龙女","郭靖"],2)
['郭靖', '张三']

各位亲们慢走!
Python的数字函数