數(shù)字類型
Python 語言提供了3種數(shù)字類型:整數(shù)、浮點(diǎn)數(shù)和復(fù)數(shù)槐脏。
布爾型 In addition, Booleans are a subtype of integers.
整數(shù)類型(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)符號腾务,如表所示。
進(jìn)制種類 | 引導(dǎo)符號 | 描述 |
---|---|---|
十進(jìn)制 | 無 | 默認(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ū)分大小寫 |
整數(shù)類型的取值范圍在理論上沒有限制窿撬,實(shí)際上受限制于運(yùn)行Python程序的計算機(jī)內(nèi)存大小启昧。
Integers have unlimited precision.
浮點(diǎn)數(shù)類型(float)表示有小數(shù)點(diǎn)的數(shù)值。浮點(diǎn)數(shù)有兩種表示方法:小數(shù)表示和科學(xué)計數(shù)法表示劈伴。
Python浮點(diǎn)數(shù)的取值范圍和小數(shù)精度受不同計算機(jī)系統(tǒng)的限制密末,sys.float_info詳細(xì)列出了Python解釋器所運(yùn)行系統(tǒng)的浮點(diǎn)數(shù)各項參數(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
以下表格來自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ù)類型直接表示或科學(xué)計數(shù)法中的系數(shù)(E或e前面的數(shù))最長可輸出16個數(shù)字严里,浮點(diǎn)數(shù)運(yùn)算結(jié)果中最長輸出17個數(shù)字新啼。然而根據(jù)sys.float_info.dig的值,計算機(jī)只能提供15個數(shù)字的準(zhǔn)確性刹碾。浮點(diǎn)數(shù)在超過15位數(shù)字計算中產(chǎn)生的誤差與計算機(jī)內(nèi)部采用二進(jìn)制運(yùn)算有關(guān)燥撞。
復(fù)數(shù)類型(complex)表示數(shù)學(xué)中的復(fù)數(shù)。復(fù)數(shù)可以看作二元有序?qū)崝?shù)對(a, b)迷帜,表示a + bj物舒,其中,a是實(shí)數(shù)部分戏锹,b為虛數(shù)部分冠胯。在Python語言中,復(fù)數(shù)的虛數(shù)部分通過后綴 'J' 或 'j' 來表示景用。
復(fù)數(shù)類型中的實(shí)數(shù)部分和虛數(shù)部分的數(shù)值都是浮點(diǎn)類型涵叮。對于復(fù)數(shù)z,可以用z.real和z.imag分別獲得它的實(shí)部和虛部伞插。
順便提一下布爾型(bool),關(guān)鍵字True和False分別表示真和假盾碗,他們的值是1和0媚污,還可和數(shù)字相加。
可以用內(nèi)置函數(shù)type()來查詢變量所指的對象類型廷雅,例如:
>>> 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ù)字類型的操作
數(shù)值運(yùn)算操作符
Python提供了9個基本的數(shù)值運(yùn)算操作符耗美。這些操作符不需要引用標(biāo)準(zhǔn)或者第三方函數(shù)庫,也叫內(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) |
注意:
- 不對復(fù)數(shù)運(yùn)算商架。整數(shù)商,即不大于x與y之商的最大整數(shù)芥玉。
1//2
結(jié)果為0蛇摸,-1//2
的結(jié)果為-1。 - 不對復(fù)數(shù)運(yùn)算灿巧。恒等式
x % y
=x - (x // y) * y
赶袄。 - Python 規(guī)定
0**0
的值為1,這也是編程語言的通用做法抠藕。
三種數(shù)字類型之間存在一種擴(kuò)展關(guān)系:int -> float -> complex饿肺。不同數(shù)字類型之間的運(yùn)算所生成的結(jié)果是更寬的類型。
表中所有的二元數(shù)學(xué)操作符(+
盾似、-
敬辣、*
、/
、//
溉跃、%
汰聋、**
)都有與之對應(yīng)的增強(qiáng)賦值操作符(+=
、-=
喊积、*=
烹困、/=
、//=
乾吻、%=
髓梅、**=
)。即x op= y
等價于 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)
可以計算復(fù)數(shù)x的模诡必。 -
round(1.5)
的值為2奢方,round(2.5)
的值也是2。 -
max()
和min()
實(shí)際上是 Common Sequence Operations爸舒。
數(shù)字類型轉(zhuǎn)換函
The constructors
int()
,float()
, andcomplex()
can be used to produce numbers of a specific type.
內(nèi)置的數(shù)字類型轉(zhuǎn)換函數(shù)可以將某種類型(數(shù)字類型或者字符串)轉(zhuǎn)換為數(shù)字類型蟋字,如下表:
函數(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') # 見 注意2
nan
>>> float('-inf') # 見 注意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庫 數(shù)學(xué)函數(shù)
math庫是Python提供的內(nèi)置數(shù)學(xué)類函數(shù)庫鹊奖,不支持復(fù)數(shù)運(yùn)算。math庫中的函數(shù)不能直接使用涂炎,需要使用import引用該庫忠聚,引用的方法有兩種:
-
import math
。以math.函數(shù)名()
形式調(diào)用函數(shù)唱捣。(建議两蟀,不會覆蓋內(nèi)置函數(shù)) -
from math import 函數(shù)名1 [,函數(shù)名2,...]
。直接以函數(shù)名()
的方式調(diào)用徐裸。特殊地,from math import *
,math庫的所有函數(shù)都可以直接使用。
實(shí)際上阀捅,所有的函數(shù)庫的應(yīng)用都可以自由選擇這兩種方式忍级。
除了明確的說明患雇,這些函數(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
True
orFalse
.-
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 % y
may 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 % y
returns a result with the sign of y instead, and may not be exactly computable for float arguments.
>>> math.fmod(-1234,3) # 結(jié)果的符號與x一致
-1.0
>>> -1234%3 # 結(jié)果的符號與y一致
2
>>> math.fmod(98765432112345679,2) # fmod函數(shù)會把x轉(zhuǎn)為float历帚,float只有有限位的精度,此時結(jié)果出錯杠娱。
0.0
>>> 98765432112345679%2 # 整數(shù)有無限的精度
1
>>> math.factorial(10.00000) # x可以是具有整數(shù)值的浮點(diǎn)數(shù)挽牢。x.is_integer()返回True。
3628800
>>> math.modf(-123.456) # 返回的整數(shù)部分是以浮點(diǎn)數(shù)的形式寫的
(-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]) #針對浮點(diǎn)數(shù)float的sum,所以叫fsum摊求。
1.0
冪函數(shù)和對數(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ù)的自然對數(shù) |
Gamma函數(shù)的性質(zhì):
- 當(dāng)
為整數(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')
.