1、decimal
# coding=UTF8
"""
create time:2022-11-17 14:31:42
@Author :wyk
"""
import decimal
decimal.getcontext().prec = 2 # 设置精度
d1 = decimal.Decimal(1.12)
d2 = decimal.Decimal(9.98)
print(d1 + d2)
print(d1 - d2)
print(d1 * d2)
print(d1 / d2)
输出结果:
2、math
# coding=UTF8
"""
create time:2022-11-17 10:49:30
@Author :wyk
"""
import math
x = -1.5
print(math.ceil(x)) # 向上取整
print(math.floor(x)) # 向下取整
print(math.fabs(x)) # 绝对值
y = 4
z = 2
print(math.fmod(y, z)) # y/z的余数,结果为浮点数
print(math.factorial(y)) # y的阶乘,1 * 2 * 3,y!
print(math.pow(y, z)) # y的z次幂
print(math.fsum((1, 2, 3, 4, 5))) # 返回迭代器中所有元素的和
print(math.gcd(y, z)) # y和z的最大公约数
print(math.sqrt(y)) # y的平方根
print(math.trunc(x)) # 返回x的整数部分
print(math.exp(z)) # e的z次幂
print(math.e) # 常量e
print(math.pi) # 常量π
输出结果:
3、random
# coding=UTF8
"""
create time:2022-11-17 14:47:35
@Author :wyk
"""
import random
print(random.random())
print(random.uniform(1.1, 9.9)) # 随机浮点数
print(random.randint(1, 10)) # 随机整数
print(random.randrange(1, 10, 2)) # 返回 [start, stop) 范围内步长为 step 的一个随机整数, 目前是1、3、5、7、9
print(random.choice('abcdef')) # 从非空序列seq返回一个随机元素
l = [1, 2, 3, 4, 5, 6]
print(random.sample(l, 3)) # 无重复随机抽样3次
random.shuffle(l) # 将序列 x 随机打乱位置
print(l)
输出结果: