Python數(shù)字類型及其操作

數(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)

注意:

  1. 不對復(fù)數(shù)運(yùn)算商架。整數(shù)商,即不大于x與y之商的最大整數(shù)芥玉。1//2結(jié)果為0蛇摸,-1//2 的結(jié)果為-1。
  2. 不對復(fù)數(shù)運(yùn)算灿巧。恒等式 x % y = x - (x // y) * y 赶袄。
  3. 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)

注意:

  1. abs(x) 可以計算復(fù)數(shù)x的模诡必。
  2. round(1.5) 的值為2奢方,round(2.5) 的值也是2。
  3. max()min() 實(shí)際上是 Common Sequence Operations爸舒。

數(shù)字類型轉(zhuǎn)換函

The constructors int(), float(), and complex() 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.

注意:

  1. 小數(shù)部分被直接舍去;see functions math.floor() and math.ceil() for well-defined conversions.
  2. 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引用該庫忠聚,引用的方法有兩種:

  1. import math。以math.函數(shù)名()形式調(diào)用函數(shù)唱捣。(建議两蟀,不會覆蓋內(nèi)置函數(shù))
  2. 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)

注意

  1. Return an integral value.

  2. Retrun True or False.

  3. 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.
  4. Note that the x % y may not return the same result with math.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) e^{x}
math.expm1(x) e^{x}-1 more accurate than math.exp(x) - 1 for x near zero
math.log(x[, base]) {\log_{base}}^{x}
math.log1p(x) \ln (1+x) more accurate than math.log(1+x) for x near zero
math.log2(x) {\log_{2}}^{x} more accurate than math.log(x, 2)
math.log10(x) {\log_{10}}^{x} more accurate than math.log(x, 10)
math.pow(x, y) x^{y} 1
math.sqrt(x) \sqrt {x}

注意:

  1. Unlike the built-in ** operator, math.pow() converts both its arguments to type float. Use ** or the built-in pow() function for computing exact integer powers.
三角函數(shù)

與角度有關(guān)的量均為弧度禽拔。

函數(shù) 描述 返回值 注意
math.acos(x) \arccos (x) [0 , \pi]
math.asin(x) \arcsin (x) [-{\pi}/2, + {\pi}/2]
math.atan(x) \arctan (x) [-{\pi}/2, + {\pi}/2]
math.atan2(y,x) \arctan ({y}/{x}) or \arctan (y /x) \pm \pi [-{\pi}, + {\pi}] 1
math.cos(x) \cos (x) [-1 ,1]
math.hypot(x, y) \sqrt {x^{2} + y^{2}} [0,+\infty]
math.sin(x) \sin (x) [-1,1]
math.tan(x) \tan (x) [-\infty, +\infty]

注意:

  1. 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) {\rm arccosh} (x) = \ln (x+\sqrt {x^{2}-1})
math.asinh(x) {\rm arcsinh} (x) = \ln (x+\sqrt {x^{2}+1})
math.atanh(x) {\rm arctanh} (x) = \frac {1} {2} \ln{\frac {1+x} {1-x}}
math.cosh(x) \cosh (x) = \frac{e^{x} + e^{-x}} {2}
math.sinh(x) \sinh (x) = \frac{e^{x} - e^{-x}} {2}
math.tanh(x) \tanh (x) = \frac{e^{x} - e^{-x}} {e^{x} + e^{-x}}
特殊函數(shù)
函數(shù) 描述
math.erf(x) \frac {2} {\sqrt {\pi}} \int _{0}^{x} e^{ -t ^{2}} dt 高斯誤差函數(shù)
math.erfc(x) \frac {2} {\sqrt {\pi}} \int _{x}^{+\infty} e^{ -t ^{2}} dt 余補(bǔ)高斯誤差函數(shù)
math.gamma(x) \int _{0} ^{+\infty} t^{x-1} e^{-t} dt Gamma函數(shù)
math.lgamma(x) \ln (\int _{0} ^{+\infty} t^{x-1} e^{-t} dt) Gamma函數(shù)的自然對數(shù)

Gamma函數(shù)的性質(zhì):

  1. \Gamma (x+1) = x \Gamma (x)
  2. 當(dāng)x為整數(shù)時,\Gamma (n+1) = n!
  3. \Gamma (\frac {1} {2}) = \sqrt {\pi}
>>> math.factorial(10)
3628800
>>> math.gamma(11)
3628800.0
數(shù)學(xué)常數(shù)
常數(shù) 數(shù)學(xué)表示 描述 注意
math.pi \pi 圓周率
math.e e 自然常數(shù)
math.tau \tau =2 \pi 圓周率的兩倍
math.inf + \infty A floating-point positive infinity 1
math.nan A floating-point “not a number” (NaN) value. 2

注意:

  1. Equivalent to the output of float('inf'). For negative infinity, use -math.inf.
  2. Equivalent to the output of float('nan').
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末室叉,一起剝皮案震驚了整個濱河市睹栖,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌太惠,老刑警劉巖磨淌,帶你破解...
    沈念sama閱讀 211,884評論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異凿渊,居然都是意外死亡梁只,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評論 3 385
  • 文/潘曉璐 我一進(jìn)店門埃脏,熙熙樓的掌柜王于貴愁眉苦臉地迎上來搪锣,“玉大人,你說我怎么就攤上這事彩掐」怪郏” “怎么了?”我有些...
    開封第一講書人閱讀 157,435評論 0 348
  • 文/不壞的土叔 我叫張陵堵幽,是天一觀的道長狗超。 經(jīng)常有香客問我,道長朴下,這世上最難降的妖魔是什么努咐? 我笑而不...
    開封第一講書人閱讀 56,509評論 1 284
  • 正文 為了忘掉前任,我火速辦了婚禮殴胧,結(jié)果婚禮上渗稍,老公的妹妹穿的比我還像新娘。我一直安慰自己团滥,他們只是感情好竿屹,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,611評論 6 386
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著灸姊,像睡著了一般拱燃。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上厨钻,一...
    開封第一講書人閱讀 49,837評論 1 290
  • 那天扼雏,我揣著相機(jī)與錄音坚嗜,去河邊找鬼。 笑死诗充,一個胖子當(dāng)著我的面吹牛苍蔬,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播蝴蜓,決...
    沈念sama閱讀 38,987評論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼碟绑,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了茎匠?” 一聲冷哼從身側(cè)響起格仲,我...
    開封第一講書人閱讀 37,730評論 0 267
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎诵冒,沒想到半個月后凯肋,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,194評論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡汽馋,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,525評論 2 327
  • 正文 我和宋清朗相戀三年侮东,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片豹芯。...
    茶點(diǎn)故事閱讀 38,664評論 1 340
  • 序言:一個原本活蹦亂跳的男人離奇死亡悄雅,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出铁蹈,到底是詐尸還是另有隱情宽闲,我是刑警寧澤,帶...
    沈念sama閱讀 34,334評論 4 330
  • 正文 年R本政府宣布握牧,位于F島的核電站容诬,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏沿腰。R本人自食惡果不足惜放案,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,944評論 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望矫俺。 院中可真熱鬧,春花似錦掸冤、人聲如沸厘托。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,764評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽铅匹。三九已至,卻和暖如春饺藤,著一層夾襖步出監(jiān)牢的瞬間包斑,已是汗流浹背流礁。 一陣腳步聲響...
    開封第一講書人閱讀 31,997評論 1 266
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留罗丰,地道東北人神帅。 一個月前我還...
    沈念sama閱讀 46,389評論 2 360
  • 正文 我出身青樓,卻偏偏與公主長得像萌抵,于是被迫代替她去往敵國和親找御。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,554評論 2 349

推薦閱讀更多精彩內(nèi)容