Python Numeric Types

来自KlniuWiki
跳转到: 导航, 搜索

本文描述的是Python的数据类型:数字类型,包含int(整型)、float(浮点)、complex numbers(复数)、fixed-precision decimal(固定精度小数)、fraction(分式)、sets、booleans(布尔)。

目录

1 基本

1.1 文法

1234, -24, 0, 9999999999999          #Integers, 整数, 不限大小
1.23, 1, 3.14e-10, 4E210, 4.0e+210   #Floating-point numbers, 浮点数
0o177, 0x9ff, 0b101010               #octal, hex, binary, 八进制, 十六进制, 二进制
3+4j, 3.0+4.0j, 3j                   #complex number, 复数

1.2 进制

十六进制:由数字0和字母x或X再加十六进制的数字组成,如0x1F, 0X1f, 支持的操作:

hex(16)        #'0x10', hex(number) -> string, Return the hexadecimal representation of an integer or long integer.
int('16',16)   #22, 以十六进制转化字符串为整数

八进制:由数字0和字母o或O再加八进制的数字组成,如0o117, 0O117

oct(16)        #'0o20', oct(number) -> string, Return the octal representation of an integer or long integer.
int('16',8)    #14, 以八进制转化字符串为整数

二进制:由数字0和字母b或B再加二进制的数字组成,如0b0101, 0B0101

bin(16)        #'0b10000', bin(number) -> string, Return the binary representation of an integer or long integer.
int('11',2)    #3, 以二进制转化字符串为整数

1.3 复数

复数由实部和虚部组成,虚部数字后带字母j或J,支持的操作:

complex(10, 12) #(10+12j) 构造一个复数

1.4 内置工具

支持的操作符:+ - * / >> &

内置数学函数:pow, abs, round, int, hex, bin, oct

模块: random, math

2 操作

2.1 数字显示

示例:

num = 1/3.0             #0.3333333333333333, 机器内部显示
print(num)              #0.333333333333, 友好输出
repr(num)               #'0.3333333333333333', 将机器内部的变量以字符串的形式显示
str(num)                #'0.333333333333',以字符串显示
'%e' % num              #'3.333333e-01', 字符串格式化输出(指数形式)
'%4.2f' % num           #'0.33', 字符串格式化输出(浮点形式)
'{0:4.2f}'.format(num)  #'0.33', 字符串格式化输出(浮点形式)

2.2 比较操作符

示例:

1 < 2                  #True, Less than
2.0 >= 1               #True, Greater than or equal: mixed-type 1 converted to 1.0
2.0 == 2.0             #True, Equal value
2.0 != 2.0             #False, Not equal value
 
X = 2
Y = 4
Z = 6
X < Y < Z              #True, Chained comparisons: range tests, 连续比较,python支持, wow
X < Y and Y < Z        #True
X < Y > Z              #False
X < Y and Y > Z        #False
 
1 < 2 < 3.0 < 4        #True
1 > 2 > 3.0 > 4        #False
1 == 2 < 3             #False, Same as: 1 == 2 and 2 < 3, Not same as: False < 3 (which means 0 < 3, which is true)

2.3 除法

/表示真除法,保留小数;//表示floor, 向最小数字保留,即2.5保留为2.0,-2.5保留为-3.0

10 / 4            # 2.5, keeps remainder
10 // 4           # 2, truncates remainder
10 / 4.0          # 2.5, keeps remainder
10 // 4.0         # 2.0, truncates to floor

Floor和截断的区别:

import math
math.floor(2.5)     # 2
math.floor(-2.5)    # -3
math.trunc(2.5)     # 2
math.trunc(-2.5)    # -2

2.4 位操作符

或: | 与: & 异或: ^ 左移: << 右移: >>

x = 1               # 0001
x << 2              # 4, Shift left 2 bits: 0100
x | 2               # 3, Bitwise OR: 0011
x & 1               # 1, Bitwise AND: 0001
 
X = 0b0001          # Binary literals
X << 2              # 4, Shift left
bin(X << 2)         # '0b100', Binary digits string
bin(X | 0b010)      # '0b11', Bitwise OR
bin(X & 0b1)        # '0b1', Bitwise AND
X = 0xFF            # Hex literals
bin(X)              # '0b11111111'
X ^ 0b10101010      # 85, Bitwise XOR
bin(X ^ 0b10101010) # '0b1010101'
int('1010101', 2)   # 85, String to int per base

2.5 math模块

math模块包含一些数学计算的工具,示例:

import math
math.pi, math.e                               # (3.1415926535897931, 2.7182818284590451), Common constants
math.sin(2 * math.pi / 180)                   # 0.034899496702500969, Sine, tangent, cosine
math.sqrt(144), math.sqrt(2)                  # (12.0, 1.4142135623730951), Square root
pow(2, 4), 2 ** 4                             # (16, 16), Exponentiation (power)
pow(4, .5)                                    # 2.0, same as math.sqrt(4)
abs(-42.0), sum((1, 2, 3, 4))                 # (42.0, 10), Absolute value, summation
min(3, 1, 2, 4), max(3, 1, 2, 4)              # (1, 4), Minimum, maximum
math.floor(2.567), math.floor(-2.567)         # (2, 3), Floor (next-lower integer)
math.trunc(2.567), math.trunc(2.567)         # (2, 2), Truncate (drop decimal digits)
int(2.567), int(2.567)                        # (2, 2), Truncate (integer conversion)
round(2.567), round(2.467), round(2.567, 2)   # (3, 2, 2.5699999999999998), Round (Python 3.0 version)
'%.1f' % 2.567, '{0:.2f}'.format(2.567)       # ('2.6', '2.57'), Round for display (Chapter 7

2.6 random模块

random模块用于生成从0到1之间的随机数,生成两个整数之间的随机整数,从一个序列中随机取出一个值。示例:

import random
random.random()                                                     # 0.44694718823781876
random.random()                                                     # 0.28970426439292829
random.randint(1, 10)                                               # 5
random.randint(1, 10)                                               # 4
random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])   # 'Life of Brian'
random.choice(['Life of Brian', 'Holy Grail', 'Meaning of Life'])   # 'Holy Grail'

3 Decimal 类型

浮点数在计算机内的存储并不与人类想象的那样准确,因此就出现了Decimal类型,它比 float 更接近我们在学样里学习的数学计算结果;使用Decimal需要先导入Decimal模块。示例:

0.1 + 0.1 + 0.1 - 0.3                                               # 5.5511151231257827e-17
print(0.1 + 0.1 + 0.1 - 0.3)                                        # 5.55111512313e-17
from decimal import Decimal
Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')   # Decimal('0.0')

Decimal可以设置精度,示例:

import decimal
decimal.Decimal(1) / decimal.Decimal(7)     # Decimal('0.1428571428571428571428571429')
decimal.getcontext().prec = 4
decimal.Decimal(1) / decimal.Decimal(7)     # Decimal('0.1429')

临时设置精度:

import decimal
decimal.Decimal('1.00') / decimal.Decimal('3.00')           # Decimal('0.3333333333333333333333333333')
with decimal.localcontext() as ctx:
    ctx.prec = 2
    decimal.Decimal('1.00') / decimal.Decimal('3.00')       # Decimal('0.33')
decimal.Decimal('1.00') / decimal.Decimal('3.00')           # Decimal('0.3333333333333333333333333333')

4 Fraction类型

Fraction是一个有理数类,也就是说,可以用分式来表示数字,这样就可以在运算时不损失精度。而且Fraction支持分式的计算,就像我们小学时学习的一样。Fraction使用时也必须先导入模块。

from fractions import Fraction
x = Fraction(1, 3)                    # Fraction(1, 3), Numerator, denominator
y = Fraction(4, 6)                    # Fraction(2, 3), Simplified to 2, 3 by gcd
print(y)                              # 2/3
x + y                                 # Fraction(1, 1)
x – y                                # Fraction(-1, 3), Results are exact: numerator, denominator
x * y                                 # Fraction(2, 9)

Fraction同时支持从一个字符串类型的浮点数构造分式:

Fraction('.25')                     # Fraction(1, 4)
Fraction('1.25')                    #Fraction(5, 4)
Fraction('.25') + Fraction('1.25')  # Fraction(3, 2)

5 数值精度

源于机器存储浮点型数值的特点,数值在计算起来是不那么精确的,因此python引入了Deciaml和Fraction来控制数值的精度,示例:

a = 1 / 3.0                                                             # 0.33333333333333331, Only as accurate as floating-point hardware
b = 4 / 6.0                                                             # 0.66666666666666663, Can lose precision over calculations
a + b                                                                   # 1.0
a - b                                                                   # -0.33333333333333331
a * b                                                                   # 0.22222222222222221
0.1 + 0.1 + 0.1 - 0.3                                                   # 5.5511151231257827e-17, This should be zero (close, but not exact)
 
from fractions import Fraction
Fraction(1, 10) + Fraction(1, 10) + Fraction(1, 10) - Fraction(3, 10)   # Fraction(0, 1)
 
from decimal import Decimal
Decimal('0.1') + Decimal('0.1') + Decimal('0.1') - Decimal('0.3')       # Decimal('0.0')
1 / 3                                                                   # 0.33333333333333331
Fraction(1, 3)                                                          # Fraction(1, 3), Numeric accuracy
 
import decimal
decimal.getcontext().prec = 2
decimal.Decimal(1) / decimal.Decimal(3)                                 # Decimal('0.33')

6 数值转换和不同数据类型之间的运算

Fraction、float之间是可以相互转换的,示例:

(2.5).as_integer_ratio()               # (5, 2), float object method
f = 2.5
z = Fraction(*f.as_integer_ratio())    # Fraction(5, 2), Convert float -> fraction: two args, Same as Fraction(5, 2)
x = Fraction(1, 3)                     # Fraction(1, 3)
x + z                                  # Fraction(17, 6), 5/2 + 1/3 = 15/6 + 2/6
float(x)                               # 0.33333333333333331, Convert fraction -> float
float(z)                               # 2.5
float(x + z)                           # 2.8333333333333335
17 / 6                                 # 2.8333333333333335
Fraction.from_float(1.75)              # Fraction(7, 4), Convert float -> fraction: other way
Fraction(*(1.75).as_integer_ratio())   # Fraction(7, 4)

不同数值类型之间相加,会将某一类型转换为另一类型后进行计算。示例:

1 + 2.0                 # 3.0, int + float -> float
x = Fraction(1, 3)      # Fraction(1, 3)
x + 2                   # Fraction(7, 3), Fraction + int -> Fraction
x + 2.0                 # 2.3333333333333335, Fraction + float -> float
x + (1./3)              # 0.66666666666666663, Fraction + float -> float
x + (4./3)              # 1.6666666666666665
x + Fraction(4, 3)      # Fraction(5, 3), Fraction + Fraction -> Fraction

在从float到Fraction转换时,是肯定要损失精度的,因为float的存储就决定了它已经不再精确了,因此,当需要的时候,我们可以限制float转换为Fraction时分母的最大值。示例:

4.0 / 3                                         # 1.3333333333333333
(4.0 / 3).as_integer_ratio()                    # (6004799503160661, 4503599627370496), Precision loss from float
x = Fraction(1, 3)
a = x + Fraction(*(4.0 / 3).as_integer_ratio()) # Fraction(22517998136852479, 13510798882111488)
22517998136852479 / 13510798882111488.          # 1.6666666666666667, 5 / 3 (or close to it!)
a.limit_denominator(10)                         # Fraction(5, 3), Simplify to closest fraction

7 Sets(集合)

set 类似于数学中的集合,它有以下特性:

  1. 可以修改。
  2. 值不能重复。
  3. 可以包含任意类型的值。
  4. 类似于dict的键集合。
  5. 有集合的很多特性。
  6. 只能存储不可以修改的对象(hashable),例如list, dict、set,就不可以添加到set内,不过可以存储tuple。

示例:

set([1, 2, 3, 4])            # {1, 2, 3, 4}, Built-in call
{1, 2, 3, 4}                 # 3.0 set literals, same as above
set('spam')                  # {'a', 'p', 's', 'm'}, Add all items in an iterable
 
S = {'s', 'p', 'a', 'm'}
S.add('alot')                # {'a', 'p', 's', 'm', 'alot'}, add an item
S.update([1, 2])             # {'a', 1, 2, 'm', 'p', 's', 'alot'}, Merge: in-place union, 从list添加元素
S.update((3, 4))             # {'a', 1, 2, 3, 4, 'm', 'p', 's', 'alot'},从tuple添加元素
S.update({5, 6})             # {'a', 1, 2, 3, 4, 5, 6, 'm', 'p', 's', 'alot'}, 从set添加元素
S.remove(1)                # {'a', 2, 3, 4, 5, 6, 'm', 'p', 's', 'alot'}, delete item 1

set支持数学集合的很多运算,示例:

S1 = {1, 2, 3, 4}
S1 & {1, 3}                          # {1, 3}, Intersection, 交集
{1, 5, 3, 6} | S1                    # {1, 2, 3, 4, 5, 6}, Union, 并集
S1 - {1, 3, 4}                       # {2}, Difference, 差集
S1 > {1, 3}                          # True, Superset, 父集
S1 ^ {1, 3}                          # {2, 4}, 异或
{1, 2, 3} | {3, 4}                   # {1, 2, 3, 4}
{1, 2, 3} | [3, 4]                   # TypeError: unsupported operand type(s) for |: 'set' and 'list'
{1, 2, 3}.union([3, 4])              # {1, 2, 3, 4}
{1, 2, 3}.union({3, 4})              # {1, 2, 3, 4}
{1, 2, 3}.union(set([3, 4]))         # {1, 2, 3, 4}
{1, 2, 3}.intersection((1, 3, 5))    # {1, 3}, intersection, 交集
{1, 2, 3}.issubset(range(-5, 5))     # True, 是否子集

set不能存储list、dict、set,可以存储tuple:

S = {1.23}
S.add([1, 2, 3])                   # TypeError: unhashable type: 'list', Only mutable objects work in a set
S.add({'a':1})                     # TypeError: unhashable type: 'dict'
S.add((1, 2, 3))                   # {1.23, (1, 2, 3)}, No list or dict, but tuple okay

Set comprehension:

{x ** 2 for x in [1, 2, 3, 4]}         # {16, 1, 4, 9}, 3.0 set comprehension, Give me a new set containing X squared, for every X in a list
{x for x in 'spam'}                    # {'a', 'p', 's', 'm'}, Same as: set('spam')
{c * 4 for c in 'spam'}                # {'ssss', 'aaaa', 'pppp', 'mmmm'}, Set of collected expression results

8 Booleans(布尔值)

bool在python中是int的子集,true和false分别为1和0,但其类型确实为bool,因为这个特性,bool可以用来与int数值计算,但不建议这么做:

type(True)               # <class 'bool'>
isinstance(True, int)    # True
True == 1                # True, Same value
True is 1                # False, But different object: see the next chapter
True or False            # True, Same as: 1 or 0
True + 4                 # 5, (Hmmm)

9 参考文献

  • Mark Lutz. Learning Python, Fourth Edition[M]. United States of America:Newgen North America,2009.09.[2011-08-10]. ISBN:978-0-596-15806-4.
个人工具
分类
化学
[×] 國學
学佛
[×] 数学
物理
生活
[×] 英语
读书
辞典
廣告