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)

猜你喜欢

转载自blog.csdn.net/vitas_fly/article/details/80268104