8.python中的數字


  python中數字對象的創建如下,

a = 123
b = 1.23
c = 1+1j

  可以直接輸入數字,然后賦值給變量。

  同樣也可是使用類的方式:

a = int(123)
b = float(1.23)
c = complex(1+1j)

  但一般不用類的方式創建,直接輸入數字就好了。

  python中的數字包括了整型 int ,長整型 long , 浮點型 float , 復數 complex ,其差別為:

int(整型)

  也稱有符號整數,只有正或負整數,不帶小數點。
  其和長整型在於整數有一定的位數限制:
    在32位機器上,整數的位數為32位,取值范圍為-2**31~2**31-1,即-2147483648~2147483647
    在64位系統上,整數的位數為64位,取值范圍為-2**63~2**63-1,即-9223372036854775808~9223372036854775807
  一旦超過位數,則會自動轉換為長整型(python2.2以后的版本)
 
long(長整型)
  理論上是無限長的,但數據終究是儲存在內存中的,所以實際長度限制取決於內存的大小

float(浮點型)
  帶有小數的數字都被稱為浮點型
 
complex(復數)
  就是數學中的復數,定義和數學中的一樣(z=a+bi,這里a和b是實數,i是虛數單位,例如1+5j)
 

一.整型

 
Help on class int in module __builtin__:

class int(object)
 |  int(x=0) -> int or long
 |  int(x, base=10) -> int or long
 |  
 |  Convert a number or string to an integer, or return 0 if no arguments
 |  are given.  If x is floating point, the conversion truncates towards zero.
 |  If x is outside the integer range, the function returns a long instead.
 |  
 |  If x is not a number or if base is given, then x must be a string or
 |  Unicode object representing an integer literal in the given base.  The
 |  literal can be preceded by '+' or '-' and be surrounded by whitespace.
 |  The base defaults to 10.  Valid bases are 0 and 2-36.  Base 0 means to
 |  interpret the base from the string as an integer literal.
 |  >>> int('0b100', base=0)
 |  4
 |  
 |  Methods defined here:
 |  
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |  
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |  
 |  __and__(...)
 |      x.__and__(y) <==> x&y
 |  
 |  __cmp__(...)
 |      x.__cmp__(y) <==> cmp(x,y)
 |  
 |  __coerce__(...)
 |      x.__coerce__(y) <==> coerce(x, y)
 |  
 |  __div__(...)
 |      x.__div__(y) <==> x/y
 |  
 |  __divmod__(...)
 |      x.__divmod__(y) <==> divmod(x, y)
 |  
 |  __float__(...)
 |      x.__float__() <==> float(x)
 |  
 |  __floordiv__(...)
 |      x.__floordiv__(y) <==> x//y
 |  
 |  __format__(...)
 |  
 |  __getattribute__(...)
 |      x.__getattribute__('name') <==> x.name
 |  
 |  __getnewargs__(...)
 |  
 |  __hash__(...)
 |      x.__hash__() <==> hash(x)
 |  
 |  __hex__(...)
 |      x.__hex__() <==> hex(x)
 |  
 |  __index__(...)
    '''用於切片,但不接受參數,返回的是整個數字,所以切片對數字而言沒有意義'''
 |      x[y:z] <==> x[y.__index__():z.__index__()]  
 |  
 |  __int__(...)
 |      x.__int__() <==> int(x)
 |  
 |  __invert__(...)
 |      x.__invert__() <==> ~x
 |  
 |  __long__(...)
 |      x.__long__() <==> long(x)
 |  
 |  __lshift__(...)
 |      x.__lshift__(y) <==> x<<y
 |  
 |  __mod__(...)
 |      x.__mod__(y) <==> x%y
 |  
 |  __mul__(...)
 |      x.__mul__(y) <==> x*y
 |  
 |  __neg__(...)
 |      x.__neg__() <==> -x
 |  
 |  __nonzero__(...)
 |      x.__nonzero__() <==> x != 0
 |  
 |  __oct__(...)
 |      x.__oct__() <==> oct(x)
 |  
 |  __or__(...)
 |      x.__or__(y) <==> x|y
 |  
 |  __pos__(...)
 |      x.__pos__() <==> +x
 |  
 |  __pow__(...)
 |      x.__pow__(y[, z]) <==> pow(x, y[, z])
 |  
 |  __radd__(...)
 |      x.__radd__(y) <==> y+x
 |  
 |  __rand__(...)
 |      x.__rand__(y) <==> y&x
 |  
 |  __rdiv__(...)
 |      x.__rdiv__(y) <==> y/x
 |  
 |  __rdivmod__(...)
 |      x.__rdivmod__(y) <==> divmod(y, x)
 |  
 |  __repr__(...)
 |      x.__repr__() <==> repr(x)
 |  
 |  __rfloordiv__(...)
 |      x.__rfloordiv__(y) <==> y//x
 |  
 |  __rlshift__(...)
 |      x.__rlshift__(y) <==> y<<x
 |  
 |  __rmod__(...)
 |      x.__rmod__(y) <==> y%x
 |  
 |  __rmul__(...)
 |      x.__rmul__(y) <==> y*x
 |  
 |  __ror__(...)
 |      x.__ror__(y) <==> y|x
 |  
 |  __rpow__(...)
 |      y.__rpow__(x[, z]) <==> pow(x, y[, z])
 |  
 |  __rrshift__(...)
 |      x.__rrshift__(y) <==> y>>x
 |  
 |  __rshift__(...)
 |      x.__rshift__(y) <==> x>>y
 |  
 |  __rsub__(...)
 |      x.__rsub__(y) <==> y-x
 |  
 |  __rtruediv__(...)
 |      x.__rtruediv__(y) <==> y/x
 |  
 |  __rxor__(...)
 |      x.__rxor__(y) <==> y^x
 |  
 |  __str__(...)
 |      x.__str__() <==> str(x)
 |  
 |  __sub__(...)
 |      x.__sub__(y) <==> x-y
 |  
 |  __truediv__(...)
 |      x.__truediv__(y) <==> x/y
 |  
 |  __trunc__(...)
 |      Truncating an Integral returns itself.
 |  
 |  __xor__(...)
 |      x.__xor__(y) <==> x^y
 |  
 |  bit_length(...)
 |      int.bit_length() -> int
 |      '''返回改數字用二進制要幾位來表示'''
 |      Number of bits necessary to represent self in binary.
 |      >>> bin(37)  #得出其二進制表示形式
 |      '0b100101'  #0b是二進制的標識,用來說明其是二進制形式,其后的100101才是真正的二進制代碼
 |      >>> (37).bit_length()
 |      6  #37的二進制表示是 100101,一共6位,所以返回6
 |  
 |  conjugate(...)
 |      Returns self, the complex conjugate of any int.
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  denominator
 |      the denominator of a rational number in lowest terms
 |  
 |  imag
 |      the imaginary part of a complex number
 |  
 |  numerator
 |      the numerator of a rational number in lowest terms
 |  
 |  real
 |      the real part of a complex number
 |  
 |  ----------------------------------------------------------------------
 |  Data and other attributes defined here:
 |  
 |  __new__ = <built-in method __new__ of type object>
 |      T.__new__(S, ...) -> a new object with type S, a subtype of T
int

 

可以看出其內置方法分為3種:

  1.普通方法(已經在代碼中注釋說明)

  2.相當於某些內置函數的方法(參考這里

  3.與運算符相關的方法

這里詳細介紹一下python的運算符:

1.算數運算符

  以下假設變量a=10,變量b=20

 

2.比較運算符

  以下假設變量a=10,變量b=20

  關於python中比較運算符使用的總結:

  1.python中任意對象都可以比較

  2.相同類型的對象(實例),如果是數字型(int/float/long/complex),則按照簡單的大小來比較;如果是非數字型,且類(型)中定義了__cmp__(含__gt__,__lt__等)則按照__cmp__來比較,否則按照地址(id)來比較。

  3.不同類型的對象(實例),如果其中一個比較對象是數字型(int/float/long/complex等),則數字型的對象<其它非數字型的對象;如果兩個都是非數字型的對象,則按照類型名的順序比較,如{} < "abc"(按照"dict" < "str"),而"abc" > [1,2], "abc" < (1,2)。

  4.對於自定義的類(型)實例,如果繼承自基本類型,則按照基本類型的規則比較(1-3)。否則,old-style class < new-style class, new-style class之間按照類型名順序比較,old-style class之間按照地址進行比較。

  5.bool類型是int的子類,且True=1, False=0,比較時按照1-4來比較,如True > -1, True < 4.2, True < "abc"等
  
  這部分內容 轉載於: 戳這里


3.賦值運算符

  以下假設變量a=10,變量b=20

4.位運算符

  按位運算符是把數字看作二進制來進行計算的。Python中的按位運算法則如下:

  下表中變量 a = 60,b = 13

5.邏輯運算符

  以下假設變量 a = 10, b=20

 

6.成員運算符

  除了以上的一些運算符之外,Python還支持成員運算符,測試實例中包含了一系列的成員,包括字符串,列表或元組。

 

7.身份運算符

  身份運算符用於比較兩個對象的存儲單元

 

  這里要講講python中的內存池(緩沖池)了,python使用內存池來管理小的整型數和小的字符串等等。
  什么意思呢?

  當我們執行以下賦值運算時

a = 123
b = 123

 

  理論上是要分別在內存中創建兩個值,然后賦值給變量的,但是這樣做實在是有點浪費,明明是一樣的數,卻要占用兩個內存空間。

  所以python為了節約內存,引入了內存池,當小的整型(-5~257,不包括257)要多次創建時,只創建一次,后面的都將引用指向同一個地方,此時使用身份運算符會出現:

  字符串的則以256個ascll碼為分界

  有興趣的可以參考:戳這里

 

8.運算符的優先級

  另外,我們也可以像數學一樣使用括號() ,來指定某個運算先進行

  更多參考:戳這里

  有別人做好的輪子就是不一樣,一路復制粘貼就好了,真輕松。


 

二、長整型

  和整型基本一樣,這里就不重復了。自己可以用 help() 函數查看。
  遇事不決喊救命

 


 

三、浮點型

   這里就不全部列舉了,只講講不同的。

 |  __setformat__(...)
 |      float.__setformat__(typestr, fmt) -> None
 |      
 |      You probably don't want to use this function.  It exists mainly to be
 |      used in Python's test suite.
 |      
 |      typestr must be 'double' or 'float'.  fmt must be one of 'unknown',
 |      'IEEE, big-endian' or 'IEEE, little-endian', and in addition can only be
 |      one of the latter two if it appears to match the underlying C reality.
 |      
 |      Override the automatic determination of C-level floating point type.
 |      This affects how floats are converted to and from binary strings.

 

  一個內部方法,用於內部測試的,官方都說了You probably don't want to use this function(你可能不想使用這個函數),而實際上我們也用不到,我也不知道有什么用,一般可以無視。

 

 |  __trunc__(...)
 |      Return the Integral closest to x between 0 and x.

  返回最接近x從0積分和x,貌似和積分運算有關,沒用過

 

 

 |  as_integer_ratio(...)
 |      float.as_integer_ratio() -> (int, int)
 |      
 |      Return a pair of integers, whose ratio is exactly equal to the original
 |      float and with a positive denominator.
 |      Raise OverflowError on infinities and a ValueError on NaNs.
 |      
 |      >>> (10.0).as_integer_ratio()
 |      (10, 1)
 |      >>> (0.0).as_integer_ratio()
 |      (0, 1)
 |      >>> (-.25).as_integer_ratio()
 |      (-1, 4)

  返回一個由兩個數字組成的元祖,而兩個數字相除就等於原浮點數,其實就是返回一個最簡分數,分子在前面,分母在后面。

 

 

 |  conjugate(...)
 |      Return self, the complex conjugate of any float.

  返回本身的共軛復數

 

 |  fromhex(...)
 |      float.fromhex(string) -> float
 |      
 |      Create a floating-point number from a hexadecimal string.
 |      >>> float.fromhex('0x1.ffffp10')
 |      2047.984375
 |      >>> float.fromhex('-0x1p-1074')
 |      -4.9406564584124654e-324

  用一個十六進制的字符串來創建一個浮點數

 

 

 |  hex(...)
 |      float.hex() -> string
 |      
 |      Return a hexadecimal representation of a floating-point number.
 |      >>> (-0.1).hex()
 |      '-0x1.999999999999ap-4'
 |      >>> 3.14159.hex()
 |      '0x1.921f9f01b866ep+1'

  上面方法的逆運算,返回一個浮點數的十六進制表示的字符串

 

 

 |  is_integer(...)
 |      Return True if the float is an integer.

  判斷一個浮點數是否為整數

  其實就是看小數位是否都為0

 


 

四、復數

  都是一些運算和內置函數相關的,唯一特別的是

 |  conjugate(...)
 |      complex.conjugate() -> complex
 |      
 |      Return the complex conjugate of its argument. (3-4j).conjugate() == 3+4j.

   返回一個原復數的共軛復數

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM