數(shù)字類(lèi)型
Python 語(yǔ)言提供了3種數(shù)字類(lèi)型:整數(shù)、浮點(diǎn)數(shù)和復(fù)數(shù)。
布爾型 In addition, Booleans are a subtype of integers.
整數(shù)類(lèi)型(int)與數(shù)學(xué)中整數(shù)概念一致,共有4種進(jìn)制表示:十進(jìn)制,二進(jìn)制,八進(jìn)制和十六進(jìn)制。默認(rèn)情況,整數(shù)采用十進(jìn)制,其它進(jìn)制需要增加相應(yīng)的引導(dǎo)符號(hào),如表所示。
| 進(jìn)制種類(lèi) | 引導(dǎo)符號(hào) | 描述 |
|---|---|---|
| 十進(jìn)制 | 無(wú) | 默認(rèn)情況 |
| 二進(jìn)制 | 0b 或 0B | 由字符0和1組成 |
| 八進(jìn)制 | 0o 或 0O | 由字符0到7組成 |
| 十六進(jìn)制 | 0x 或 0X | 由字符0到9、a到f、A到F組成,不區(qū)分大小寫(xiě) |
整數(shù)類(lèi)型的取值范圍在理論上沒(méi)有限制,實(shí)際上受限制于運(yùn)行Python程序的計(jì)算機(jī)內(nèi)存大小。
Integers have unlimited precision.
浮點(diǎn)數(shù)類(lèi)型(float)表示有小數(shù)點(diǎn)的數(shù)值。浮點(diǎn)數(shù)有兩種表示方法:小數(shù)表示和科學(xué)計(jì)數(shù)法表示。
Python浮點(diǎn)數(shù)的取值范圍和小數(shù)精度受不同計(jì)算機(jī)系統(tǒng)的限制,sys.float_info詳細(xì)列出了Python解釋器所運(yùn)行系統(tǒng)的浮點(diǎn)數(shù)各項(xiàng)參數(shù),例如:
>>> import sys
>>> sys.float_info
sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308, min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53, epsilon=2.220446049250313e-16, radix=2, rounds=1)
>>> sys.float_info.max
1.7976931348623157e+308
以下表格來(lái)自Python官網(wǎng)的Documentation。
| Attribute | Explanation |
|---|---|
| epsilon | difference between 1 and the least value greater than 1 that is representable as a float |
| dig | maximum number of decimal digits that can be faithfully represented in a float |
| mant_dig | float precision: the number of base-radix digits in the significand of a float |
| max | maximum representable finite float |
| max_exp | maximum integer e such that radix**(e-1) is a representable finite float |
| max_10_exp | maximum integer e such that 10**e is in the range of representable finite floats |
| min | minimum positive normalized float |
| min_exp | minimum integer e such that radix**(e-1) is a normalized float |
| min_10_exp | minimum integer e such that 10**e is a normalized float |
| radix | radix of exponent representation |
| rounds | integer constant representing the rounding mode used for arithmetic operations. |
浮點(diǎn)數(shù)類(lèi)型直接表示或科學(xué)計(jì)數(shù)法中的系數(shù)(E或e前面的數(shù))最長(zhǎng)可輸出16個(gè)數(shù)字,浮點(diǎn)數(shù)運(yùn)算結(jié)果中最長(zhǎng)輸出17個(gè)數(shù)字。然而根據(jù)sys.float_info.dig的值,計(jì)算機(jī)只能提供15個(gè)數(shù)字的準(zhǔn)確性。浮點(diǎn)數(shù)在超過(guò)15位數(shù)字計(jì)算中產(chǎn)生的誤差與計(jì)算機(jī)內(nèi)部采用二進(jìn)制運(yùn)算有關(guān)。
復(fù)數(shù)類(lèi)型(complex)表示數(shù)學(xué)中的復(fù)數(shù)。復(fù)數(shù)可以看作二元有序?qū)崝?shù)對(duì)(a, b),表示a + bj,其中,a是實(shí)數(shù)部分,b為虛數(shù)部分。在Python語(yǔ)言中,復(fù)數(shù)的虛數(shù)部分通過(guò)后綴 'J' 或 'j' 來(lái)表示。
復(fù)數(shù)類(lèi)型中的實(shí)數(shù)部分和虛數(shù)部分的數(shù)值都是浮點(diǎn)類(lèi)型。對(duì)于復(fù)數(shù)z,可以用z.real和z.imag分別獲得它的實(shí)部和虛部。
順便提一下布爾型(bool),關(guān)鍵字True和False分別表示真和假,他們的值是1和0,還可和數(shù)字相加。
可以用內(nèi)置函數(shù)type()來(lái)查詢(xún)變量所指的對(duì)象類(lèi)型,例如:
>>> 1+True-False
2
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
<class 'int'> <class 'float'> <class 'bool'> <class 'complex'>
數(shù)字類(lèi)型的操作
數(shù)值運(yùn)算操作符
Python提供了9個(gè)基本的數(shù)值運(yùn)算操作符。這些操作符不需要引用標(biāo)準(zhǔn)或者第三方函數(shù)庫(kù),也叫內(nèi)置操作符。
| Operation | Result | Notes |
|---|---|---|
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 | (1) |
x % y |
remainder of x / y | (2) |
-x |
x negated | |
+x |
x unchanged | |
x ** y |
x to the power y | (3) |
注意:
- 不對(duì)復(fù)數(shù)運(yùn)算。整數(shù)商,即不大于x與y之商的最大整數(shù)。
1//2結(jié)果為0,-1//2的結(jié)果為-1。 - 不對(duì)復(fù)數(shù)運(yùn)算。恒等式
x % y=x - (x // y) * y。 - Python 規(guī)定
0**0的值為1,這也是編程語(yǔ)言的通用做法。
三種數(shù)字類(lèi)型之間存在一種擴(kuò)展關(guān)系:int -> float -> complex。不同數(shù)字類(lèi)型之間的運(yùn)算所生成的結(jié)果是更寬的類(lèi)型。
表中所有的二元數(shù)學(xué)操作符(+、-、*、/、//、%、**)都有與之對(duì)應(yīng)的增強(qiáng)賦值操作符(+=、-=、*=、/=、//=、%=、**=)。即x op= y 等價(jià)于 x = x op y ,op 為二元數(shù)學(xué)操作符。
數(shù)值運(yùn)算函數(shù)
內(nèi)置的數(shù)值運(yùn)算函數(shù),如下表:
| 函數(shù) | 描述 | 注意 |
|---|---|---|
abs(x) |
absolute value or magnitude of x | (1) |
divmid(x, y) |
the pair (x // y, x % y) | |
pow(x,y [,z]) |
Return x to the power y; if z is present, return x to the power y, modulo z (computed more efficiently than pow(x, y) % z) | |
round(x [,ndigits]) |
x rounded to n digits, rounding half to even. If n is omitted, it defaults to 0 | (2) |
max(x1,x2...,xn) |
smallest item of x1, x2, ... xn | (3) |
min(x1,x2,...xn) |
largest item of x1, x2, ... xn | (3) |
注意:
-
abs(x)可以計(jì)算復(fù)數(shù)x的模。 -
round(1.5)的值為2,round(2.5)的值也是2。 -
max()和min()實(shí)際上是 Common Sequence Operations。
數(shù)字類(lèi)型轉(zhuǎn)換函
The constructors
int(),float(), andcomplex()can be used to produce numbers of a specific type.
內(nèi)置的數(shù)字類(lèi)型轉(zhuǎn)換函數(shù)可以將某種類(lèi)型(數(shù)字類(lèi)型或者字符串)轉(zhuǎn)換為數(shù)字類(lèi)型,如下表:
| 函數(shù) | 描述 | 注意 |
|---|---|---|
int(x) |
x converted to integer | (1) |
float(x) |
x converted to floating point | (2) |
complex(re, [im]) |
a complex number with real part re, imaginary part im. im defaults to zero. |
注意:
- 小數(shù)部分被直接舍去;see functions
math.floor()andmath.ceil()for well-defined conversions. - float also accepts the strings “nan” and “inf” with an optional prefix “+” or “-” for Not a Number (NaN) and positive or negative infinity.
>>> int(10.9898)
10
>>> int('10.9898') # 解釋器拋出 ValueError,并給出基本描述
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '10.9898'
>>> int('10')
10
>>> float('10.8989')
10.8989
>>> complex('10.8989')
(10.8989+0j)
>>> float(10+0j) # 解釋器拋出 TypeError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't convert complex to float
>>> float('+nan') # 見(jiàn) 注意2
nan
>>> float('-inf') # 見(jiàn) 注意2
-inf
其他函數(shù)
float.as_integer_ratio()
Return a pair of integers whose ratio is exactly equal to the original float and with a positive denominator. Raises OverflowError on infinities and a ValueError on NaNs.
float.is_integer()
Return True if the float instance is finite with integral value, and False otherwise:
>>> 3.1416926.as_integer_ratio()
(3537231405668161, 1125899906842624)
>>> _[0]/_[1]
3.1416926
>>> 3.000.is_integer()
True
math庫(kù) 數(shù)學(xué)函數(shù)
math庫(kù)是Python提供的內(nèi)置數(shù)學(xué)類(lèi)函數(shù)庫(kù),不支持復(fù)數(shù)運(yùn)算。math庫(kù)中的函數(shù)不能直接使用,需要使用import引用該庫(kù),引用的方法有兩種:
-
import math。以math.函數(shù)名()形式調(diào)用函數(shù)。(建議,不會(huì)覆蓋內(nèi)置函數(shù)) -
from math import 函數(shù)名1 [,函數(shù)名2,...]。直接以函數(shù)名()的方式調(diào)用。特殊地,from math import *,math庫(kù)的所有函數(shù)都可以直接使用。
實(shí)際上,所有的函數(shù)庫(kù)的應(yīng)用都可以自由選擇這兩種方式。
除了明確的說(shuō)明,這些函數(shù)的返回值為浮點(diǎn)數(shù)。
數(shù)論和表示函數(shù)
| 函數(shù) | 描述 | 注意 |
|---|---|---|
math.ceil(x) |
The smallest integer reater than or equal to x | (1) |
math.copysign(x, y) |
Return a float with the absolute value of x but the sign of y | |
math.fabs(x) |
Return the absolute value of x. | |
math.factorial(x) |
Return x factorial | (3) |
math.floor(x) |
the largest integer less than or equal to x | (1) |
math.fmod(x, y) |
返回x與y的模 | (4) |
math.frexp(x) |
||
math.fsum(iterable) |
Return an accurate floating point sum of values in the iterable | |
math.gcd(a, b) |
Return the greatest common divisor of the integers a and b. | (1)(3) |
math.isclose(a, b) |
Return True if the values a and b are close to each other and False otherwise. |
(2) |
math.isfinite(x) |
Return True if x is neither an infinity nor a NaN, and False otherwise. |
(2) |
math.isinf(x) |
Return True if x is a positive or negative infinity, and False otherwise. |
(2) |
math.isnan(x) |
Return True if x is a NaN (not a number), and False otherwise. |
(2) |
math.ldexp(x, i) |
||
math.modf(x) |
Return the fractional and integer parts of x. | |
math.remainder(x,y) |
||
math.trunc(x) |
Return the Real value x truncated to an Integral | (1) |
注意
Return an integral value.
Retrun
TrueorFalse.-
Only accept parameter(s) of integral value.
-
math.factorial(x)raises ValueError if x in not integral or negative. -
math.gcd(a,b)raises TypeError if either a or b is not integral.
-
Note that the
x % ymay not return the same result withmath.fmod(x,y).
fmod(x, y)is exactly (mathematically; to infinite precision) equal to x - n*y for some integer n such that the result has the same sign as x and magnitude less than abs(y).x % yreturns a result with the sign of y instead, and may not be exactly computable for float arguments.
>>> math.fmod(-1234,3) # 結(jié)果的符號(hào)與x一致
-1.0
>>> -1234%3 # 結(jié)果的符號(hào)與y一致
2
>>> math.fmod(98765432112345679,2) # fmod函數(shù)會(huì)把x轉(zhuǎn)為float,float只有有限位的精度,此時(shí)結(jié)果出錯(cuò)。
0.0
>>> 98765432112345679%2 # 整數(shù)有無(wú)限的精度
1
>>> math.factorial(10.00000) # x可以是具有整數(shù)值的浮點(diǎn)數(shù)。x.is_integer()返回True。
3628800
>>> math.modf(-123.456) # 返回的整數(shù)部分是以浮點(diǎn)數(shù)的形式寫(xiě)的
(-0.45600000000000307, -123.0)
>>> sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
0.9999999999999999
>>> math.fsum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) #針對(duì)浮點(diǎn)數(shù)float的sum,所以叫fsum。
1.0
冪函數(shù)和對(duì)數(shù)函數(shù)
| 函數(shù) | 描述 | 注意 |
|---|---|---|
| math.exp(x) | ||
| math.expm1(x) | more accurate than math.exp(x) - 1 for x near zero |
|
| math.log(x[, base]) | ||
| math.log1p(x) | more accurate than math.log(1+x) for x near zero |
|
| math.log2(x) | more accurate than math.log(x, 2)
|
|
| math.log10(x) | more accurate than math.log(x, 10)
|
|
| math.pow(x, y) | 1 | |
| math.sqrt(x) |
注意:
- Unlike the built-in
**operator,math.pow()converts both its arguments to type float. Use**or the built-inpow()function for computing exact integer powers.
三角函數(shù)
與角度有關(guān)的量均為弧度。
| 函數(shù) | 描述 | 返回值 | 注意 |
|---|---|---|---|
math.acos(x) |
|||
math.asin(x) |
|||
math.atan(x) |
|||
math.atan2(y,x) |
|
1 | |
math.cos(x) |
|||
math.hypot(x, y) |
|||
math.sin(x) |
|||
math.tan(x) |
注意:
- Return atan(y / x), in radians. The result is between -pi and pi. The vector in the plane from the origin to point (x, y) makes this angle with the positive X axis. The point of atan2() is that the signs of both inputs are known to it, so it can compute the correct quadrant for the angle.
>>> math.atan(-1)
-0.7853981633974483
>>> math.atan2(-1,1)
-0.7853981633974483
>>> math.atan2(1,-1)
2.356194490192345
角度轉(zhuǎn)換函數(shù)
| 函數(shù) | 描述 |
|---|---|
math.degrees(x) |
Convert angle x from radians to degrees. |
math.radians(x) |
Convert angle x from degrees to radians. |
雙曲函數(shù)
| 函數(shù) | 描述 |
|---|---|
math.acosh(x) |
|
math.asinh(x) |
|
math.atanh(x) |
|
math.cosh(x) |
|
math.sinh(x) |
|
math.tanh(x) |
特殊函數(shù)
| 函數(shù) | 描述 | |
|---|---|---|
math.erf(x) |
高斯誤差函數(shù) | |
math.erfc(x) |
余補(bǔ)高斯誤差函數(shù) | |
math.gamma(x) |
Gamma函數(shù) | |
math.lgamma(x) |
Gamma函數(shù)的自然對(duì)數(shù) |
Gamma函數(shù)的性質(zhì):
- 當(dāng)
為整數(shù)時(shí),
![]()
>>> math.factorial(10)
3628800
>>> math.gamma(11)
3628800.0
數(shù)學(xué)常數(shù)
| 常數(shù) | 數(shù)學(xué)表示 | 描述 | 注意 |
|---|---|---|---|
math.pi |
圓周率 | ||
math.e |
自然常數(shù) | ||
math.tau |
圓周率的兩倍 | ||
math.inf |
A floating-point positive infinity | 1 | |
math.nan |
A floating-point “not a number” (NaN) value. | 2 |
注意:
- Equivalent to the output of
float('inf'). For negative infinity, use-math.inf. - Equivalent to the output of
float('nan').