-
模块
math 模块、cmath 模块
Python 中数学运算常用的函数基本都在 math 模块、cmath 模块中。
Python math 模块提供了许多对浮点数的数学运算函数。
Python cmath 模块包含了一些用于复数运算的函数。
cmath 模块的函数跟 math 模块函数基本一致,区别是 cmath 模块运算的是复数,math 模块运算的是数学运算。
内置模块 math、random、fractions、decimel
内置函数round()
math.fabs()等均为行为/方法
-
绝对值
import math n1 = -2 print(math.fabs(n1))
-
取整
n2 = -1.98 print(int(n2)) # -1 print(n2 // 1) # -2.0 print(math.floor(n2))#向下取整 -2 print(math.ceil(n2))#向上取整 -1 print(round(n2))#四舍五入 -2 print(math.trunc(n2))#截断小数位 -1
-
随机数
import random print(random.random()) #伪随机数,0到1的随机 print(round(random.random()*100)) #[0,100] print(math.ceil(random.random()*100)) #[1,100] print(round(random.random()*30)+50) #[50,80] print(random.choice('hello')) print(random.choice(range(100))) #[0,100] print(random.randint(0, 100)) # [0,100]的整数
random.randrange ([start,] stop [,step]) 方法返回指定递增基数集合中的一个随机数,基数缺省值为1。
print(random.randrange(0,500,5))#在[0,500]范围步长为5的随机数
shuffle()将序列的所有元素随机排序
arr=[1,2,3,4,5,6,7] random.shuffle(arr) #将序列的所有元素随机排序 print(arr)
-
decimal
import decimal #保留多少小数 n4=101.8988 print(round(n4,3)) print(decimal.Decimal(n4).quantize(decimal.Decimal('0.00')))
-
分数
import fractions f=fractions.Fraction(3,5) print(f) # 3/5 f = f + 1 print(f) # 8/5
Python-4-数据类型-续Numbers(math、random、decimal、fractions)
最新推荐文章于 2021-07-15 17:26:04 发布