Python 初学之math模块/random模块/decimal模块/fractions模块

来源:互联网 发布:贝多芬梅毒 知乎 编辑:程序博客网 时间:2024/06/14 12:00

1.math模块



>>> dir(math)

['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'hypot', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc']


math.e

math.pi

math.copysign(x,y):返回与y同号的x值。

math.ceil(x);返回<=x的最小整数

math.floor(x):返回>=x 的最大整数

math.hypot(x,y):返回sqrt(x*x + y*y)

math.modf(x);返回x的小数部分和整数部分

math.trunc(x);返回x的整数部分

math.pow(x,y):返回x**y

math.log(x,a):返回返回以a为底x的对数,若不指定参数a,默认为e

math.log10(x)



2.random模块

random.random():生成一个0<=x,1的随机浮点数

random.uniform();生成一个指定范围内的随机浮点数

random.randint(a,b):生成一个a<=x<=b之间的整数

random.randrange(a,b,step):生成一个随机数

random.choice(sequence):从序列中获取一个随机元素,列表元组字符串

random.shuffle(list):打乱列表

random.sample(sequence,k):从序列中随机获取指定长度为k的片段。



3.decimal模块

getcontext().prec,设定小数点的精度。

>>> from decimal import Decimal,getcontext>>> print(Decimal('1.0')/Decimal('3.0'))0.3333333333333333333333333333>>> getcontext().prec = 6>>> print(Decimal('1.0')/Decimal('3.0'))0.333333

4.fractions模块

用于表现和处理分数

>>> from fractions import Fraction>>> print Fraction(1,3)1/3




原创粉丝点击