python基礎-numeric types

數值類型(numeric types)

integers(整型)

什麼是整數

數學上,整數是指正整數、零、負整數。python中也是如此。

整型可表示的範圍

sys.maxsize
An integer giving the maximum value a variable of type Py_ssize_t can take. It’s usually 2**31 - 1 on a 32-bit platform and 2**63 - 1 on a 64-bit platform.

floating point numbers(浮點數)

科學計數法

科學記數法是一種記數的方法。把一個數表示成a與10的n次冪相乘的形式(1≤|a|<10,n爲整數),這種記數法叫做科學記數法,在計算機中,10的冪通常用E或e來計數,例如,$ 31415926 = 3.1415926\ast10^7 = 3.1415926E7$

什麼是浮點數

指一個數的小數點的位置不是固定的,是可以浮動的。浮點數在計算機中的存儲規則是根據 IEEE 754標準。

浮點數是屬於有理數中某特定子集的數的數字表示,在計算機中以近似表示任意某個實數。具體的說,這個實數由一個整數或定點數(即尾數)乘以某個基數(計算機中通常是2)的整數次冪得到,這種表示方法類似於基數爲10的科學記數法。

python中的浮點數

python中的浮點數是64位的雙精度浮點數,可使用十進制或科學計數法表示。它的實現還是採用c語言的double float。

IEEE754 標準 64位雙精度 計算機表示爲 1S/11E/52M

1S (signed)表示符號位,用來表示正、負,佔1個bit;

11E (exponent)表示階碼,可以理解爲浮點數的 整數 或者說是指數部分,佔11個bit;

52M (mantissa)表示尾數,可以理解爲小數部分,或者說精度,佔52個bit;

浮點數可表示的範圍

使用sys.float_info 查看本機的浮點數的精度以及內部表徵

attribute float.h macro explanation
epsilon DBL_EPSILON difference between 1.0 and the least value greater than 1.0 that is representable as a float
dig DBL_DIG maximum number of decimal digits that can be faithfully represented in a float; see below
mant_dig DBL_MANT_DIG float precision: the number of base-radix digits in the significand of a float
max DBL_MAX maximum representable positive finite float
max_exp DBL_MAX_EXP maximum integer e such that radix**(e-1) is a representable finite float
max_10_exp DBL_MAX_10_EXP maximum integer e such that 10**e is in the range of representable finite floats
min DBL_MIN minimum representable positive normalized float
min_exp DBL_MIN_EXP minimum integer e such that radix**(e-1) is a normalized float
min_10_exp DBL_MIN_10_EXP minimum integer e such that 10**e is a normalized float
radix FLT_RADIX radix of exponent representation
rounds FLT_ROUNDS integer constant representing the rounding mode used for arithmetic operations. This reflects the value of the system FLT_ROUNDS macro at interpreter startup time. See section 5.2.4.2.2 of the C99 standard for an explanation of the possible values and their meanings.

complex numbers(複數)

複數由實數部分和虛數部分構成,可以用a + bj,或者complex(a,b)表示, 複數的實部a和虛部b都是浮點型。

複數的特點:

  1. 複數由實數部分和虛數部分構成
  2. 虛部不能單獨存在,它總是和一個值爲 0.0 的實部一起構成一個複數。
  3. 表示虛部的語法: real + imag j
  4. 實部和虛部都是浮點數
  5. 虛部必須有後綴 j 或 J。

運算符

基本算數運算

Operation Result
x + y sum of x and y
x - y difference of x and y
x * y product of x and y
x / y quotient of x and y
x // y floored quotient of x and y
x % y remainder of x / y
-x x negated
+x x unchanged
abs(x) absolute value or magnitude of x
int(x) x converted to integer
float(x) x converted to floating point
complex(re, im) a complex number with real part re, imaginary part im. im defaults to zero.
c.conjugate() conjugate of the complex number c
divmod(x, y) the pair (x // y, x % y)
pow(x, y) x to the power y
x ** y x to the power y
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章