当前位置:首页>python>Python拓展模块:算数模块

Python拓展模块:算数模块

  • 2026-10-11 07:59:41
Python拓展模块:算数模块
 一、math 和 cmath 模块 
  • math模块支持浮点数运算
math.sin()math.cos()math.tan()math.pimath.log(x,a)math.pow(x,y) #幂 
  • cmath模块支持复数运算
cmath.polar()  #极坐标cmath.rect()   #笛卡尔坐标cmath.exp()    #e的x次方cmath.log(x,a) #以a为底x的对数cmath.iog10(x) #以10为底x的对数cmath.sqrt(x)  #x的平方根
 二、decimal模块 
  • 小数--固定精度的浮点值
#导入模块from decimal import Decimal
  • 生成小数
a = Decimal("0.1")b = Decimal("0.2")

⚠️ 参数最好用字符串。

  • 小数运算
#加法from decimal import Decimala = Decimal("0.1")b = Decimal("0.2")print(a + b)
#减法Decimal("1.5") - Decimal("0.3")
#乘法Decimal("2.5") * Decimal("3")
#除法Decimal("1") / Decimal("3")
  • 设置精度

fromdecimal import getcontextgetcontext().prec = 4
#示例from decimal import Decimal, getcontextgetcontext().prec = 4print(Decimal("1") / Decimal("3"))#输出0.3333

 三、fractions 模块 

  • 分数--实现了一个有理数对象
#导入模块from fractions import Fraction
  • 生成分数

✔️ 直接用分子/分母

f = Fraction(3, 4)print(f)   # 3/4

✔️ 用字符串(推荐,最精确)

f = Fraction("0.75")print(f)   # 3/4

✔️ 用整数

f = Fraction(5)print(f)   # 5
  • 浮点数转换为分数
Fraction.from_float(1.75)

⚠️ 尽管可以把浮点数转换为分数,在某些情况下,这么做会有不可避免的精度损失,因为这个数字在其最初的浮点形式上是不精确的。

  • 分数运算
a = Fraction(1, 3)b = Fraction(1, 6)print(a + b)   # 1/2print(a - b)   # 1/6print(a * b)   # 1/18print(a / b)   # 2
 四、random 模块 
  • 伪随机数
计算机中的随机函数是按照一定的算法模拟产生的,其结果是确定的,是可预见的。
  • 随机数种子
随机种子相同,随机数的序列也是相同的。
random.seed(a = None)
  • random 模块常用函数

1️⃣random()--生成 [0~1) 之间的随机小数

random.random()

✔️常见用途:概率模拟,权重计算,随机比例

2️⃣uniform(a, b)--指定范围的随机浮点数

random.uniform(1, 10)#可能输出7.23819

✔️特点:可以生成小数,范围可控

3️⃣randint(a, b)--指定范围[a,b]之间随机整数(最常用)

random.randint(1, 6)

✔️应用:掷骰子,抽奖编号,随机选人

4️⃣randrange()--类似 range 的随机整数

random.randrange(start, stop, step)

5️⃣choice()--指定序列中随机选一个元素

random.choice(list)random.choice(["A", "B", "C"])

6️⃣choices()--可重复抽样

random.choices(list, k=3)random.choices(["A", "B", "C"], k=3)#抽K位

✔️特点:可以重复

7️⃣sample()--不重复抽样

random.sample(list, k)random.sample(["A", "B", "C", "D"], 2)

8️⃣shuffle()--打乱列表

random.shuffle(list)
a = [1, 2, 3, 4]random.shuffle(a)print(a)#输出[3, 1, 4, 2]

⚠️ 注意:直接修改原列表(in-place)

最新文章

随机文章