Python-数学模块(math,random)
(1)引入模块:import math
ceil()
向上取整操作
格式:math.ceil(数值); 返回值:整型;
[code]import math s = math.ceil(12.34) print(s) #结果为:13
floor()
向下取整操作
格式:math.floor(数值); 返回值:整型;
[code]import math s = math.floor(12.34) print(s) #结果为:12
round()
四舍五入操作
格式:round(数值); 返回值:整数;
[code]s = round(12.52) print(s) #结果为:13 #保留两位小数的方式 kw = round(12.525, 2) print(kw) #结果为:12.53
pow()
计算一个数值的N次方
格式: math.pow(底数,幂); 返回值:浮点类型;
[code]import math s = math.pow(2,4) print(s) #结果为:16.0
sqrt()
开平方
格式:math.sqrt(数值); 返回值:浮点数;
[code]import math s = math.sqrt(9) print(s) #结果为:3
fabs()
对一个数值获取其绝对值操作
格式:math.fabs(数值); 返回值:浮点数;
[code]import math s = math.fabs(-12) print(s) #结果为:12.0
abs()
对一个数值获取其绝对值操作
格式:abs(数值); 返回值:可能是整数可以能浮点数(根据原数据的类型而定);
[code]import math s = abs(-12) print(s) #结果为:12 kw = abs(-12.0) print(kw) #结果为:12.0
modf()
将一个浮点数拆成小数和整数部分组成的元组
格式:math.modf(数值); 返回值:元组;
[code]import math s = math.modf(12.2) print(s) #结果为:(0.1999999999999993, 12.0)
copysign()
将第二个数的正负号复制给第一个数
格式:math.copysign(值1,值2); 返回值:值1 符号是值2的正负号;
[code]import math s = math.copysign(-10, 1) print(s) #结果为:10.0 kw = math.copysign(11, -1) print(kw) #结果为:-11.0
fsum()
将一个序列的数值进行相加求和
格式:math.fsum(序列); 返回值:浮点数
[code]import math s = math.fsum([1,2,3,4,5]) print(s) #结果为:15.0
sum()
将一个序列的数值进行相加求和
格式:sum(序列); 返回值:数值类型;
[code]import math s = sum([1,2,3,4,5]) print(s) #结果为:15
pi
圆周率
[code]import math s = math.pi print(s) #结果为:3.141592653589793
e
自然对数
[code]import math s = math.e print(s) #结果为:2.718281828459045
(2)引入模块:import random
random()
获取0~1之间的随机小数包含0不包含1
格式:random.random(); 返回值:浮点数;
[code]import random s = random.random() print(s) #结果例如为:0.7380083855970431
choice()
随机获取列表中的值
格式:random.choice(序列); 返回值:序列中的某个值;
[code]import random s = random.choice([1,5,2,3,6]) print(s) #结果例如为:6
shuffle()
随机打乱序列
格式:random.shuffle(序列); 返回值:打乱顺序的序列
[code]import random s = [1,2,3,4,5] random.shuffle(s) print(s) #结果例如为:[3, 4, 5, 1, 2]
randrange()
获取指定范围内指定间隔的随机整数数
格式:random.randrange(开始值,结束值[,间隔值]); 返回值:整数;
[code]import random s = random.randrange(0,10,2) print(s)
uniform()
随机获取指定范围内的所有数值包括小数
格式:random.uniform(开始值,结束值); 返回值:随机返回范围内的所有数值(浮点型);
[code]import random s = random.uniform(1,5) print(s) #结果例如为:3.0839659638433954
- Python标准库12 数学与随机数 (math包,random包)
- python3 模块math(数学公式)
- Python标准库12 数学与随机数 (math包,random包)
- Python Imaging Library: ImageMath Module(图像数学运算模块)
- Python标准库12 数学与随机数 (math包,random包)
- Python标准库12 数学与随机数 (math包,random包)
- Python数学与随机数 (math包,random包)
- Python标准库数学与随机数 (math包,random包)
- Python标准库12 数学与随机数 (math包,random包)(转)
- 洗礼灵魂,修炼python(13)--模块random,math,pickle
- Python学习笔记17:标准库之数学相关(math包,random包)
- Python标准库12 数学与随机数 (math包,random包)
- Python基础笔记_Day04_数据类型、math模块、random模块、string模块
- Python标准库12 数学与随机数 (math包,random包)
- Python标准库12 数学与随机数 (math包,random包)
- Python random模块
- python学习笔记1:math.pow()和np.random.choice()
- [ Python - 5 ] 通过random模块生成随机字符串
- Python random模块sample、randint、shuffle、choice随机函数概念和应用
- Python random模块打乱数组顺序