1. 程式人生 > >PythonCookBook 筆記 chapter-03-數值

PythonCookBook 筆記 chapter-03-數值

1,round函式, 跟format()格式化輸出區分開

>>> round(5.123, 2) # 取整到固定小數位
5.12
>>> round(5.128, 2)
5.13
>>> round(-5.128, 2)
-5.13
>>> round(-5.123, 2)
-5.12
>>> round(-5.125, 2) # 當值正好是一半時,取離值最接近的偶數上
-5.12
>>> round(-5.125, -1) # 引數時負數時候,取證到十位百威
-10.0
>>> round(-5.125, -2)
-0.0
>>> 
>>> x = 123213213.898989
>>> format(x, '0.2')
'1.2e+08'
>>> format(x, '0.2f')
'123213213.90'
>>> format(x, '0.23')
'123213213.89898900687695'
>>> format(x, '0.2e')
'1.23e+08'
>>> format(x, ',')
'123,213,213.898989'

2,decimal精確的小數計算

>>> from decimal import Decimal
>>> a = Decimal('9.12')
>>> b = Decimal('12.42')
>>> a+b
Decimal('21.54')
>>>
>>> from decimal import localcontext
>>> print(a/b)
0.7342995169082125603864734300
>>>
>>> with localcontext() as ctx:
	ctx.prec = 4
	print(a/b)

0.7343

3,float無窮大的幾個特殊語法inf,-inf,nan

>>> x = float('inf')
>>> y = float('-inf')
>>> z = float('nan')
>>> x,y,z
(inf, -inf, nan)
>>>
>>> import math
>>> math.isinf(x)
True
>>> math.isinf(y)
True
>>> math.isnan(z)
True
>>> 

4, NumPy庫處理大型的資料,涉及陣列,網格,向量,矩陣都可以用NumPy庫

普通陣列和NumPy陣列的運算是不同的

>>> comArray = [1,2,3,4]
>>> comArray * 2
[1, 2, 3, 4, 1, 2, 3, 4]
>>> import numpy as np
>>> npArray = np.array([1,2,3,4])
>>> npArray * 2
array([2, 4, 6, 8])

5,random

隨機數random.choice()

取樣random.sample()

打亂順序random.shuffle()

隨機整數random.randint()

隨機浮點數random.random()

6, datetime

>>> import datetime
>>> datetime.datetime.today()
datetime.datetime(2018, 5, 10, 15, 56, 26, 206399)
>>> datetime.datetime.now()
datetime.datetime(2018, 5, 10, 15, 56, 42, 839350)