python3: 數字日期和時間(1)

 

1. 數字的四捨五入

Q: 你想對浮點數執行指定精度的舍入運算python

A: 簡單的使用內置的round(value, ndigits)函數便可。git

>>> round(1.23, 1)
1.2
>>> round(1.27, 1)
1.3
>>> round(-1.27, 1)
-1.3
>>> round(1.25361,3)
1.254
>>>

當一個值恰好在兩個邊界的中間的時候, round 函數返回離它最近的偶數。 也就是說,對1.5或者2.5的舍入運算都會獲得2。算法

>>> round(1.25)
2
>>> round(2.5)
2

傳給 round() 函數的 ndigits 參數能夠是負數,這種狀況下, 舍入運算會做用在十位、百位、千位等上面。好比:數組

>>> a = 1627731
>>> round(a, -1)
1627730
>>> round(a, -2)
1627700
>>> round(a, -3)
1628000
>>>

區別:格式化()安全

>>> x = 1.23456
>>> format(x, '0.2f')
'1.23'
>>> format(x, '0.3f')
'1.235'
>>> 'value is {:0.3f}'.format(x)
'value is 1.235'
>>>

2. 執行精確的浮點數運算

decimal 模塊dom

3.數字的格式化輸出

格式化輸出單個數字的時候,可使用內置的 format() 函數,好比:函數

 
>>> x = 1234.56789

>>> # Two decimal places of accuracy
>>> format(x, '0.2f')
'1234.57'

>>> # Right justified in 10 chars, one-digit accuracy
>>> format(x, '>10.1f')
'    1234.6'

>>> # Left justified
>>> format(x, '<10.1f')
'1234.6    '

>>> # Centered
>>> format(x, '^10.1f')
'  1234.6  '

>>> # Inclusion of thousands separator
>>> format(x, ',')
'1,234.56789'
>>> format(x, '0,.1f')
'1,234.6'
>>>

若是你想使用指數記法,將f改爲e或者E(取決於指數輸出的大小寫形式)。好比:spa

>>> format(x, 'e')
'1.234568e+03'
>>> format(x, '0.2E')
'1.23E+03'
>>>

4. 二八十六進制整數

爲了將整數轉換爲二進制、八進制或十六進制的文本串, 能夠分別使用  bin() ,  oct() 或  hex()函數

5. 字節到大證書的打包於解包

6. 複數的數學運算

7. 無窮大與NaN

8. 分數運算 

9. 大型數組運算code

10.矩陣與線性代數運算orm

11.隨機選擇

Q: 你想從一個序列中隨機抽取若干元素,或者想生成幾個隨機數。

要想從一個序列中隨機的抽取一個元素,可使用 random.choice() :

>>> import random
>>> values = [1, 2, 3, 4, 5, 6]
>>> random.choice(values)
2
>>> random.choice(values)
3
>>> random.choice(values)
1
>>> random.choice(values)
4
>>> random.choice(values)
6
>>>

爲了提取出N個不一樣元素的樣本用來作進一步的操做,可使用 random.sample() :

>>> random.sample(values, 2)
[6, 2]
>>> random.sample(values, 2)
[4, 3]
>>> random.sample(values, 3)
[4, 3, 1]
>>> random.sample(values, 3)
[5, 4, 1]
>>>

若是你僅僅只是想打亂序列中元素的順序,可使用 random.shuffle() :

>>> random.shuffle(values)
>>> values
[2, 4, 6, 5, 3, 1]
>>> random.shuffle(values)
>>> values
[3, 5, 2, 1, 6, 4]
>>>

生成隨機整數,請使用 random.randint() :

>>> random.randint(0,10)
2
>>> random.randint(0,10)
5
>>> random.randint(0,10)
0
>>> random.randint(0,10)
7
>>> random.randint(0,10)
10
>>> random.randint(0,10)
3
>>>

爲了生成0到1範圍內均勻分佈的浮點數,使用 random.random() :

random 模塊使用 Mersenne Twister 算法來計算生成隨機數。這是一個肯定性算法, 可是你能夠經過 random.seed() 函數修改初始化種子。

在 random 模塊中的函數不該該用在和密碼學相關的程序中。 若是你確實須要相似的功能,可使用ssl模塊中相應的函數。 好比, ssl.RAND_bytes() 能夠用來生成一個安全的隨機字節序列。

相關文章
相關標籤/搜索