讀書筆記:LearningPython第五版 (第五章 數字型別)
阿新 • • 發佈:2018-12-12
Chap5 數字型別
5.1 數字型別基礎
Python支援基本的數字型別,以及更高階的物件,用來處理高階工作:
- integer 和 float 物件
- complex number 物件
- decimal : 固定精度物件
- fraction : fraction 數字物件
- sets : 集合
- booleans: true/false
- 內建函式: round, math, random …
5.1.1 數字字面值
Literal | Interpretation |
---|---|
1234, −24, 0, 99999999999999 | Integers (unlimited size) |
1.23, 1., 3.14e-10, 4E210, 4.0e+210 | Floating-point numbers |
0o177, 0x9ff, 0b101010 | Octal, hex, and binary literals in 3.X |
0177, 0o177, 0x9ff, 0b101010 | Octal, octal, hex, and binary literals in 2.X |
3+4j, 3.0+4.0j, 3J | Complex number literals |
set(‘spam’), {1, 2, 3, 4} | Sets: 2.X and 3.X construction forms |
Decimal(‘1.0’), Fraction(1, 3) | Decimal and fraction extension types |
bool(X), True, False | Boolean type and constants |
幾個注意的點:
- float可以是有 小數點的, 也可以是帶
e
或者E
的 - float是以C的
double
型別實現的,所以精度高 - python3的 整數已經部分 normal和long了
- python3中,十六進位制以
0x
或者0X
開頭, 八進位制以00
,0o
,0O
開頭,二進位制0b
或者0B
開頭:hex(I), oct(I), andbin(I)
型別轉換,還有int(str, base)
- python中 complex number的虛數部分用
j
或者J
, 也可以使用complex(real, imag)
建立
5.1.2 內建數字工具
- 操作符: `+, -, *, /, >>, **, &, etc.
- 函式:
pow, abs, round, int, hex, bin, etc.
- 功能模組:
random, math, etc.
5.1.3 表示式操作符
注意:
- 比較操作符可以鏈式操作:
X<Y<Z
就相當於X<Y and Y<Z
a. 操作符型別提升
當數字操作混合型別出現時,python也是先將型別提升,之後再進行操作:
graph LR
A[int] -->B[float]
B -->C[complex]
5.2 數字實戰
5.2.1 repr 和 str
在互動式環境中,對數字的輸出時, 互動echo和 print輸出的東西有時候有點不同,主要是由於repr
和str
的區別:
repr
返回更像程式碼的字串,而str
返回更人性化的字串; 有些人讓str
來做一般用途,而repr
返回更詳細的資訊。
5.2.2 比較操作
a. 鏈式比較
A < B < C #相當於 A < B and B < C
1 < 2 < 3 < 4
1 == 2 >3 # 返回false,相當於 1==2 and 2 > 3 , 這一條就不是很直觀了
b. float比較是不精確的
1.1+2.2 == 3.3
False
5.2.3 除法
X / Y # 經典除/真除
X // Y # Floor 除, 不是 truncate除
a. python3中//
除法的結果也仍然依賴於運算元型別:
>>> 10 // 4 # Use this in 2.X if truncation needed
2
>>> 10 // 4.0
2.0
在Python2中對讓/
變成python3的結果:
>>> from __future__ import division # Enable 3.X "/" behavior
>>> 10 / 4
2.5
b. Floor vs. Truncation
floor是往負無窮大取整, 而truncate是往0 取整。 //
是floor。
>>> import math
>>> math.floor(2.5) # Closest number below value
2
>>> math.floor(-2.5)
-3
>>> math.trunc(2.5) # Truncate fractional part (toward zero)
2
>>> math.trunc(-2.5)
-2
5.2.4 整數精度
Python3的整數精度是unlimited。只是說太大的整數也會需要消耗效能。
5.2.5 Complex Number
使用J
或者j
來代表虛數部分,Python有cmath
module來處理complex number,相當於math
的複數版。
>>> 1j * 1J
(-1+0j)
>>> 2 + 1j * 3
(2+3j)
>>> (2 + 1j) * 3
(6+3j)
5.2.6 Hex, Octal, Binary: Literals and Conversions
十六進位制以0x
或者0X
開頭, 八進位制以00
,0o
,0O
開頭,二進位制0b
或者0B
開頭: hex(I), oct(I), andbin(I)
型別轉換,還有int(str, base)
a. 轉換進位制方式
oct, hex, bin
int
- string formatting:
{0:o}, {1:x}, {2:b}'.format(64, 64, 64)
'%o, %x, %x, %X' % (64, 64, 255, 255)
>>> oct(64), hex(64), bin(64) # Numbers=>digit strings
('0o100', '0x40', '0b1000000')
5.2.7 位操作
x << 2
x >> 2
x | 2 # or
x & 2 # and
x ^ 2 # xor
~x # not
python3中,直接可以呼叫的函式,都在namespace
builtins
內。
5.3 其他數字型別
5.3.1 Decimal
decimal和 float很像,但是精度是固定的。適合精確運算。
a.建立:
- Decimal(字串)
- Decimal(float)
- decimal.Decimal.from_float(1.25)
推薦第一種,因為第三種有時會導致更多精度:
>>> Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3)
Decimal('2.775557561565156540423631668E-17')
>>> 0.1 + 0.1 + 0.1 - 0.3 # Python 3.3
5.551115123125783e-17
>>> from decimal import Decimal
>>> Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')
Decimal('0.0')
當不同精度的decimal
一起運算的時,會使用精度最長的作為結果:
>>> Decimal('0.1') + Decimal('0.10') + Decimal('0.10') - Decimal('0.30')
Decimal('0.00')
b. 設定全域性精度
>>> import decimal
>>> decimal.Decimal(1) / decimal.Decimal(7) # Default: 28 digits
Decimal('0.1428571428571428571428571429')
>>> decimal.getcontext().prec = 4 # Fixed precision
>>> decimal.Decimal(1) / decimal.Decimal(7)
Decimal('0.1429')
>>> Decimal(0.1) + Decimal(0.1) + Decimal(0.1) - Decimal(0.3) # Closer to 0
Decimal('1.110E-17')
c. 區域性設定精度
with decimal.localcontext() as ctx:
ctx.prec = 2
decimal.Decimal('1.00') / decimal.Decimal('3.00')
5.3.2 Fraction
表示有理數(分數)
# 使用分子分母建立
>>> from fractions import Fraction
>>> x = Fraction(1, 3) # Numerator, denominator
>>> y = Fraction(4, 6) # Simplified to 2, 3 by gcd
>>> x
Fraction(1, 3)
>>> y
Fraction(2, 3)
>>> print(y)
2/3
# 使用小數建立
>>> Fraction('.25')
Fraction(1, 4)
>>> Fraction('1.25')
Fraction(5, 4)
# 運算
>>> x + y
Fraction(1, 1)
>>> x − y # Results are exact: numerator, denominator
Fraction(−1, 3)
>>> x * y
Fraction(2, 9)
注意: 雖然可以從float轉變成 Fraction,但是有時還是無可避免的有精度丟失,畢竟float的精度是不準確的。
>>> (4.0 / 3).as_integer_ratio() # Precision loss from float
(6004799503160661, 4503599627370496)
5.3.3 Sets
a. 操作
#建立
set([1, 2, 3, 4]) # Built-in call (all)
{1, 2, 3, 4} # Newer set literals (2.7, 3.X)
>>> 'bob' in engineers # Is bob an engineer?
>>> S.add('alot') # Methods work as before
>
>>> S1 & {1, 3} # Intersection
>>> {1, 2, 3}.intersection((1, 3, 5))
>
>>> {1, 5, 3, 6} | S1 # Union
{1, 2, 3}.union([3, 4])
>>> S1 - {1, 3, 4} # Difference
>
>>> S1 > {1, 3} # Superset
>>> {1, 2, 3}.issubset(range(-5, 5)
# set comprehension
>>> {x ** 2 for x in [1, 2, 3, 4]} # 3.X/2.7 set comprehension
b. sets的特點
sets只能包含不可變物件,因為要被hash
frozenset
可以建立 immutable set
c. set的作用
- 去重
- 排除已有的
- 比較跟順序無關的相等性
- 集合操作
5.3.4 Boolean
bool
也是一種數字型別, 是int的子集,只有0和1。
True和False
只是對0和1比較好看的表示方式而已,是重寫了str
和repr
方法,本質還是數字。