数字类型
Python 语言提供了3种数字类型:整数、浮点数和复数。
布尔型 In addition, Booleans are a subtype of integers.
整数类型(int)与数学中整数概念一致,共有4种进制表示:十进制,二进制,八进制和十六进制。默认情况,整数采用十进制,其它进制需要增加相应的引导符号,如表所示。
进制种类
引导符号
描述
十进制
无
默认情况
二进制
0b 或 0B
由字符0和1组成
八进制
0o 或 0O
由字符0到7组成
十六进制
0x 或 0X
由字符0到9、a到f、A到F组成,不区分大小写
整数类型的取值范围在理论上没有限制,实际上受限制于运行Python程序的计算机内存大小。
Integers have unlimited precision.
浮点数类型(float)表示有小数点的数值。浮点数有两种表示方法:小数表示和科学计数法表示。
Python浮点数的取值范围和小数精度受不同计算机系统的限制,sys.float_info详细列出了Python解释器所运行系统的浮点数各项参数,例如:
>>> 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官网的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.
浮点数类型直接表示或科学计数法中的系数(E或e前面的数)最长可输出16个数字,浮点数运算结果中最长输出17个数字。然而根据sys.float_info.dig的值,计算机只能提供15个数字的准确性。浮点数在超过15位数字计算中产生的误差与计算机内部采用二进制运算有关。
复数类型(complex)表示数学中的复数。复数可以看作二元有序实数对(a, b),表示a + bj,其中,a是实数部分,b为虚数部分。在Python语言中,复数的虚数部分通过后缀 'J' 或 'j' 来表示。
复数类型中的实数部分和虚数部分的数值都是浮点类型。对于复数z,可以用z.real和z.imag分别获得它的实部和虚部。
顺便提一下布尔型(bool),关键字True和False分别表示真和假,他们的值是1和0,还可和数字相加。
可以用内置函数type()来查询变量所指的对象类型,例如:
>>> 1+True-False
2
>>> a, b, c, d = 20, 5.5, True, 4+3j
>>> print(type(a), type(b), type(c), type(d))
数字类型的操作
数值运算操作符
Python提供了9个基本的数值运算操作符。这些操作符不需要引用标准或者第三方函数库,也叫内置操作符。
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)
注意:
不对复数运算。整数商,即不大于x与y之商的最大整数。1//2结果为0,-1//2 的结果为-1。
不对复数运算。恒等式 x % y = x - (x // y) * y 。
Python 规定 0**0 的值为1,这也是编程语言的通用做法。
三种数字类型之间存在一种扩展关系:int -> float -> complex。不同数字类型之间的运算所生成的结果是更宽的类型。
表中所有的二元数学操作符(+、-、*、/、//、%、**)都有与之对应的增强赋值操作符(+=、-=、*=、/=、//=、%=、**=)。即x op= y 等价于 x = x op y ,op 为二元数学操作符。
数值运算函数
内置的数值运算函数,如下表:
函数
描述
注意
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) 可以计算复数x的模。
round(1.5) 的值为2,round(2.5) 的值也是2。
max() 和 min() 实际上是 Common Sequence Operations。
数字类型转换函
The constructors int(), float(), and complex() can be used to produce numbers of a specific type.
内置的数字类型转换函数可以将某种类型(数字类型或者字符串)转换为数字类型,如下表:
函数
描述
注意
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.
注意:
小数部分被直接舍去;see functions math.floor() and math.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 "", line 1, in
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 "", line 1, in
TypeError: can't convert complex to float
>>> float('+nan') # 见 注意2
nan
>>> float('-inf') # 见 注意2
-inf
其他函数
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库 数学函数
math库是Python提供的内置数学类函数库,不支持复数运算。math库中的函数不能直接使用,需要使用import引用该库,引用的方法有两种:
import math。以math.函数名()形式调用函数。(建议,不会覆盖内置函数)
from math import 函数名1 [,函数名2,...]。直接以函数名()的方式调用。特殊地,from math import *,math库的所有函数都可以直接使用。
实际上,所有的函数库的应用都可以自由选择这两种方式。
除了明确的说明,这些函数的返回值为浮点数。
数论和表示函数
函数
描述
注意
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 or False.
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 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) # 结果的符号与x一致
-1.0
>>> -1234%3 # 结果的符号与y一致
2
>>> math.fmod(98765432112345679,2) # fmod函数会把x转为float,float只有有限位的精度,此时结果出错。
0.0
>>> 98765432112345679%2 # 整数有无限的精度
1
>>> math.factorial(10.00000) # x可以是具有整数值的浮点数。x.is_integer()返回True。
3628800
>>> math.modf(-123.456) # 返回的整数部分是以浮点数的形式写的
(-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]) #针对浮点数float的sum,所以叫fsum。
1.0
幂函数和对数函数
函数
描述
注意
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-in pow() function for computing exact integer powers.
三角函数
与角度有关的量均为弧度。
函数
描述
返回值
注意
math.acos(x)
math.asin(x)
math.atan(x)
math.atan2(y,x)
or
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
角度转换函数
函数
描述
math.degrees(x)
Convert angle x from radians to degrees.
math.radians(x)
Convert angle x from degrees to radians.
双曲函数
函数
描述
math.acosh(x)
math.asinh(x)
math.atanh(x)
math.cosh(x)
math.sinh(x)
math.tanh(x)
特殊函数
函数
描述
math.erf(x)
高斯误差函数
math.erfc(x)
余补高斯误差函数
math.gamma(x)
Gamma函数
math.lgamma(x)
Gamma函数的自然对数
Gamma函数的性质:
当
为整数时,
>>> math.factorial(10)
3628800
>>> math.gamma(11)
3628800.0
数学常数
常数
数学表示
描述
注意
math.pi
圆周率
math.e
自然常数
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').