math包包含了最基本的數學運算函數,如果想要更加高級的數學功能,可以使用標准庫外的numpy和scipy庫,他們不但支持數組和矩陣運算,
還有豐富的數學和物理方程可供使用
random包可以用來生成隨機數,隨機數不僅可以用於數學用途,還經常被嵌入到算法中
math包
1. 常數
math包主要處理數學相關的運算。math包定義了兩個常數:
math.e # 自然常數e
math.pi # 圓周率pi
2. 常用函數
math.cell(x) #對x向上取整
math.floor(x) #對x向下取整
math.pow(x, y) #x的y次方
math.log(x) #以e為低取對數
math.sqrt(x) #平方根
math.sin(x),math.cos(x),math,tan(x),math.atan(x),math.asin(x),math.acos(x)
math.degrees(x),math.radians(x) #角度和弧度互換
math.erf(x),math.gamma(x) #特殊函數
random包
1. 常用函數
- seed(a=none,version=2)
- random()
- randint(a,b)
- uniform(a,b)
- choice(x)
- shuffle(x)
- sample(x,y)
2. 事例
#coding=utf-8 import random #生成隨機浮點數(0,1) print ("random():",random.random()) #生成隨機1-10之間的整數 print ("randint():", random.randint(1,10)) #隨機生成0-20之間的偶數 print ("randrange:", random.randrange(0,21,2)) #隨機生成0-20之間的浮點數 print("uniform:", random.uniform(0,20)) #從列表序列中隨機取一個數 li = [1,2,3,4,5,6,7,8,9] print ("choice list:", random.choice(li)) print ("choice string:", random.choice("abcdef")) #對列表元素隨機排序 print ("shuffle forword:", li) random.shuffle(li) print ("shuffle back:", li) #從指定序列中獲取指定長度的片段 print ("sample:", random.sample("abcedef", 3))
3. 事例結果
>> random(): 0.5133725183742832
>>randint(): 4
>>randrange: 6
>>uniform: 3.0505739812897503
>>choice list: 2
>>choice string: a
>>shuffle forword: [1, 2, 3, 4, 5, 6, 7, 8, 9]
>>shuffle back: [4, 1, 2, 8, 6, 9, 3, 7, 5]
>>sample: ['b', 'c', 'f']