一、Python Number 類型轉換
函數 | 功能 |
---|---|
int(x [,base ]) | 將x轉換爲一個整數 |
long(x [,base ]) | 將x轉換爲一個長整數 |
float(x ) | 將x轉換到一個浮點數 |
tuple(s ) | 將序列 s 轉換爲一個元組 |
list(s ) | 將序列 s 轉換爲一個列表 |
hex(x ) | 將一個整數轉換爲一個十六進制字符串 |
二、Python數學函數
函數 | 返回值 |
---|---|
abs(x) | 返回數字的絕對值 ,如abs(-10) 返回 10 |
cmp(x, y) | 比較x,y大小,返回-1(小於),0(等於於),1 (大於) |
max(x1, x2,…) | 返回給定參數的最大值,參數可以爲序列 |
min(x1, x2,…) | 返回給定參數的最小值,參數可以爲序列 |
sqrt(x) | 返回數字x的平方根 |
math.exp(x) | e的x次冪(ex),如math.exp(1) 返回2.718281828459045 |
math.ceil(x) | 返回數字的上入整數,如math.ceil(4.1) 返回 5 |
math.floor(x) | 返回數字的下舍整數,如math.floor(4.9)返回 4 |
math.log(x,y) | math.log(100,10)返回2.0 |
math.log10(x) | math.log10(100)返回 2.0 |
三、math 模塊、cmath 模塊
Python 中數學運算常用函數基本都在 math 模塊、cmath 模塊中。
Python math:提供了許多對浮點數的數學運算函數。
Python cmath :提供了一些用於複數運算的函數。
使用:
import math #導入
dir(math) #查看 math 查看包中的內容
math.cos(math.pi) #求cos(π)
四、Python數學常量
常量 | 描述 |
---|---|
pi | 數學常量 π,用math.pi表示 |
e | 數學常量 e,用math.e表示 |
五、Python隨機數函數
常量 | 描述 |
---|---|
random() | 隨機生成下一個實數,它在[0,1)範圍內 |
choice(seq) | 從序列元素中隨機挑選一個元素,如random.choice(range(10)):0到9中隨機挑選一整數 |
uniform(x, y) | 隨機生成下一個實數,它在[x,y]範圍內。 |