一些数学操作相关的 Python 模块。如:
random:【标准库】生成伪随机数。uuid:【标准库】生成通用唯一标识符(Universally Unique ID)math:【标准库】基础数学操作,提供对底层 C 函数库的访问decimal:【标准库】提供 Decimal 数据类型用于十进制浮点运算statistics:标准库,计算数值数据的基本统计值,如均值、中位数、方差等,BUT,建议统一用 numpysympy:symbolic mathematics:符号型数学计算库,支持符号计算、高精度计算、模式匹配、绘图、解方程、微积分、组合数学、离散 数学、几何学、概率与统计、物理学等方面的功能
概述
random
random:【标准库】生成伪随机数。
1 2 3 4 5 6 7 8 9 10 11 12
| import random random.random() random.uniform(a,b) random.randint(a,b) random.randrange(start,stop,step) random.choice("hello") list1=random.shuffle(['1','3','5']) print(list1) list2=['1','3','5'] random.shuffle(list2) print(list2) print(random.sample(list(range(120)),4))
|
1 2 3
| random.choice(list_a,k=2) random.sample(list_a,k)
|
uuid
uuid:【标准库】生成通用唯一标识符(Universally Unique ID)
1 2 3 4 5
| import uuid
user_id = uuid.uuid4()
uuid.uuid1()
|
math
#最佳实践
math:【标准库】基础数学操作,提供对底层 C 函数库的访问
常用属性
常用方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| math.sqrt(4)
math.sin(x) math.cos(x) math.tan(x) matn.asin(x) math.acos(x) math.atan(x) math.degrees(x) math.log(x) math.log10(x) math.log1p:返回 x+1 的自然对数(基数为 e)的值 math.log2:返回 x 的基 2 对数 math.exp(x) math.ceil(x) math.floor(x) math.trunc(x) math.fabs(x) math.factorial(x) math.gcd(x,y) math.modf(x) math.fsum() math.isfinite(x) math.isinf(x) math.isnan(x) math.copysign(x,y)
math.pow(x,y) math.fmod(x,y) math.hypot(x,y) math.frexp()
|
decimal
decimal:【标准库】提供 Decimal 数据类型用于十进制浮点运算
- Decimal 可以模拟手工运算来避免当二进制浮点数无法精确表示十进制数时会导致的问题。
- 相比于 float 的二进制浮点实现,十进制浮点计算更为精确,能更好的控制四舍五入以满足财务应用的需求,实现用户期望结果与手工完成的计算完全一致。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| from decimal import Decimal round(0.735,2) round(float('0.735'),2) round(Decimal(0.735),2) round(Decimal('0.735'),2)
Decimal('1.00') % Decimal('.10') 1.00 % 0.10 sum([Decimal('0.1')]*10) == Decimal('1.0') sum([0.1]*10) == 1.0
decimal.getcontext().prec=100 Decimal(1)/Decimal(3)
|
statistics
statistics:标准库,计算数值数据的基本统计值,如均值、中位数、方差等,BUT,建议统一用 numpy
1 2 3 4 5
| import statistics data = [2.75, 1.75, 1.25, 0.25, 0.5, 1.25, 3.5] statistics.mean(data) statistics.median(data) statistics.variance(data)
|
sympy
sympy:symbolic mathematics:符号型数学计算库,支持符号计算、高精度计算、模式匹配、绘图、解方程、微积分、组合数学、离散 数学、几何学、概率与统计、物理学等方面的功能
- 目标是成为全功能的计算机代数系统(Computer Algebra System,CAS)
- 代码简洁、易于理解与扩展
数值类型
- 实数
- 有理数:两个整数表示有理数,
Rational(1,2) 表示 1/2 - 整数
符号表示
1 2
| import sympy x,y=sympy.Symbols
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| from sympy import
a, b, r, t = symbols('a b r t')
eq1 = (sqrt(3)*(2*r+t)/4 - a)**2 + ((2*r+t)/4 - b)**2 - r**2 eq2 = (r - a)**2 + b**2 - r**2 eq3 = (sqrt(3)*(2*r-t)/4 - a)**2 + ((2*r-t)/4 + b)**2 - r**2
c = solve([eq1, eq2], [a, b]) d = solve([eq1, eq3], [a, b])
print(c, '\n'*2, pretty(d))
|