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

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

注意:

  1. 不對(duì)復(fù)數(shù)運(yùn)算。整數(shù)商,即不大于x與y之商的最大整數(shù)。1//2結(jié)果為0,-1//2 的結(jié)果為-1。
  2. 不對(duì)復(fù)數(shù)運(yùn)算。恒等式 x % y = x - (x // y) * y 。
  3. 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 yop 為二元數(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) 可以計(jì)算復(fù)數(shù)x的模。
  2. round(1.5) 的值為2,round(2.5) 的值也是2。
  3. max()min() 實(shí)際上是 Common Sequence Operations。

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

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

注意:

  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') # 見(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ù),引用的方法有兩種:

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

注意

  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é)果的符號(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) 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ù)的自然對(duì)數(shù)

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

  1. \Gamma (x+1) = x \Gamma (x)
  2. 當(dāng)x為整數(shù)時(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)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Lua 5.1 參考手冊(cè) by Roberto Ierusalimschy, Luiz Henrique de F...
    蘇黎九歌閱讀 14,235評(píng)論 0 38
  • 第2章 基本語(yǔ)法 2.1 概述 基本句法和變量 語(yǔ)句 JavaScript程序的執(zhí)行單位為行(line),也就是一...
    悟名先生閱讀 4,503評(píng)論 0 13
  • 一、PyCharm的基本使用1.1、注釋?zhuān)簽榱朔奖阕约夯蛘咂渌瞬榭磫涡凶⑨專(zhuān)河?# 號(hào)單行注釋多行注釋: 用 ...
    IIronMan閱讀 9,072評(píng)論 3 18
  • 某一天在一次活動(dòng)中,有一個(gè)環(huán)節(jié)是未來(lái)你想做一個(gè)什么樣的人,我的一個(gè)答案是做一個(gè)有影響力的人。當(dāng)時(shí)隨手寫(xiě)的,似...
    Darli生活藝術(shù)家閱讀 494評(píng)論 1 0
  • 簡(jiǎn)介 去重是一個(gè)比較常見(jiàn)的算法,簡(jiǎn)而言之就是把一個(gè)集合中重復(fù)的項(xiàng)目去掉只保留不重復(fù)的。下面是一個(gè)JS最簡(jiǎn)單的處理。...
    jdzhangxin閱讀 1,741評(píng)論 2 4

友情鏈接更多精彩內(nèi)容