Python的数字类型及其技巧

Python中的数字类型

int
float
fractions.Fraction
decimal.Decimal

数字的舍与入

int(f):舍去小数部分,只保留整数部分,所以int(-3.8)的结果为-3
math.trunc(f):同int(f)
round(f, digits):四舍五入保留digits位小数。
math.floor(f)
math.ceil(f)

进行判断

math.isinf()
math.isfinite()
math.isnan()
float.is_integer()

如何计算幂

以下3中方法都表示开平方
math.sqrt(144)
144**0.5
pow(144,0.5)

进制转换

int(s,base):第一个参数为一个表示数字的字符串,第二个参数为进制。int('111',2)表示把二进制字符串'111'转换为整数。
oct, hex, bin:表示把一个数字转为相应的进制的字符串表示形式,所以结果都是str而不是数字。

0xfe、0b11111110、0o376和254在Python的内部都是一样的,表示数字254,这几种表示方式对Python而言没有任何差别。而'0xfe'则仅仅是一个字符串,如果需要转为整数需要借助int函数,int('0xfe',16)。

常用模块

math

用来做一些数学运算

random

用来生成一些随机数。
该模块提供了很多的function,特别有用。
random.random():产生[0,1)之间的随机数
random.randint(min, max):产生[min, max)之间的随机整数
random.choice(iterable):从可迭代对象中随机选取一个元素返回。
random.sample(iterable, k):从iterable中随机选取不重复的k个元素,以数组的形式进行返回。
random.randrange(start, stop, step):在[start, stop)中以步长step进行步进,随机产生一个元素。
random.shuffle(l):对序列进行原地随机打乱顺序,返回None。一定要注意这是原地起作用的。

decimal

如果需要结果是精准的,那么可以使用该模块。
decimal.Decimal(str):用来创建一个Decimal对象。
decimal.getcontext().prec=n:设置小数点的位数。

fractions

如果需要结果是精准的,那么可以使用该模块。
x=fractions.Fraction(1,3)
y=fractions.Fraction(0.25)
z=fractions.Fraction(*(3.25.as_integer_ratio()))

原文地址:https://www.cnblogs.com/jessonluo/p/4735692.html