数字类型实战——其他内置的数字工具

``````>>> import math
>>> math.pi, math.e # 常见常量
(3.141592653589793, 2.718281828459045)
>>> math.sin(2 * math.pi / 180) # 正弦
0.03489949670250097
>>> math.sqrt(144), math.sqrt(2) # 平方根
(12.0, 1.4142135623730951)
>>> pow(2, 4), 2 ** 4, 2.0 ** 4.0 # 求幂 (乘方)
(16, 16, 16.0)
>>> abs(-42.0), sum((1, 2, 3, 4)) # 绝对值，求和
(42.0, 10)
>>> min(3, 1, 2, 4), max(3, 1, 2, 4) # 最小值，最大值
(1, 4)
``````

``````>>> math.floor(2.567), math.floor(-2.567) # 向下取整 (下一个更小的整数)
(2, −3)
>>> math.trunc(2.567), math.trunc(−2.567) # 截断 (丢弃小数位)
(2, −2)
>>> int(2.567), int(−2.567) # 截断 (整数转换)
(2, −2)
>>> round(2.567), round(2.467), round(2.567, 2) # 四舍五入 (Python 3.X 版本)
(3, 2, 2.57)
>>> '%.1f' % 2.567, '{0:.2f}'.format(2.567) # 为显示而四舍五入 (第7章)
('2.6', '2.57')``````

``````>>> (1 / 3.0), round(1 / 3.0, 2), ('%.2f' % (1 / 3.0))
(0.3333333333333333, 0.33, '0.33')``````

``````>>> import math
>>> math.sqrt(144) # 模块
12.0
>>> 144 ** .5 # 表达式
12.0
>>> pow(144, .5) # 内置函数
12.0
>>> math.sqrt(1234567890) # 大的数字
35136.41828644462
>>> 1234567890 ** .5
35136.41828644462
>>> pow(1234567890, .5)
35136.41828644462``````

``````>>> import random
>>> random.random()
0.5566014960423105
>>> random.random() # 随机浮点数、整数、选择、乱序
0.051308506597373515
>>> random.randint(1, 10)
5
>>> random.randint(1, 10)
9``````

``````>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])
'Holy Grail'
>>> random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])
'Life of Brian'
>>> suits = ['hearts', 'clubs', 'diamonds', 'spades']
>>> random.shuffle(suits)
>>> suits