数字内置方法详解(int/long/float/complex)
一、常用方法
1.1、int
以下是Python2.7的int内置函数:
序号 | 函数名 | 作用 | 举例 |
int.bit_length() | 二进制存储这个整数至少需要多少bit(位)。 | >>> l.bit_length() >>> l = 2 >>> l.bit_length() >>> bin(2) '0b10' >>> l = 1024 >>> l.bit_length() 11 >>> bin(1024) '0b10000000000' | |
int.conjugate() | 返回复数的共轭复数 | >>> i = 1 >>> i.conjugate() >>> i = 1+1j >>> i.conjugate() (1-1j) | |
int.denominator | 返回整数分母,整数的分母是1,但是一般和fractions模块的Fraction类的实例结合使用 | >>> from fractions import Fraction >>> a = Fraction(1,2) >>> a Fraction(1, 2) >>> a.denominator | |
int.imag | 返回整数的虚数部分,如果是整数则返回0 | >>> i = 1 >>> i.imag >>> i = 1+1j >>> i.imag 1.0 >>> i = 1+2.3j >>> i.imag 2.3 | |
int.mro() | |||
int.numerator | 返回分数的分母。整数则返回本身。一般和fractions模块的Fraction类的实例结合使用 | >>> i = 2 >>> i.numerator >>> from fractions import Fraction >>> i = Fraction(2,3) >>> i.numerator | |
int.real | 返回整数的实数部分,如果是整数则返回本身。 | >>> i = 2 >>> i.real >>> i = 2 + 1j >>> i.real 2.0 |
1.2、long
以下是Python2.7的long内置函数:
序号 | 函数名 |
long.bit_length() | |
long.conjugate() | |
long.denominator | |
long.imag | |
long.mro() | |
long.numerator | |
long.real |
1.3、float
以下是Python2.7的float内置函数:
序号 | 函数名 | 作用 | 举例 |
float.as_integer_ratio() | 返回一个由两个整数元素构成的元组。这两个整数元素第一个整数除以第二个整数的商则为这个浮点数。 | >>> i = 1.5 >>> i.as_integer_ratio() (3, 2) >>> i = 1.3 >>> i.as_integer_ratio() (5854679515581645L, 4503599627370496L) >>> float(5854679515581645/4503599627370496) 1.0 >>> float(5854679515581645)/float(4503599627370496) 1.3 | |
float.conjugate() | 返回共轭浮点数 | >>> i = 1.4 >>> i.conjugate() 1.4 >>> i = 1.2 +1.4j >>> i.conjugate() (1.2-1.4j) | |
float.fromhex() | 将float.hex()转换的字符串转换成浮点型数字。 | >>> h = '0x1.8000000000000p+0' >>> f = float.fromhex(h) >>> f 1.5 | |
float.hex() | 把浮点型数字转换为十六进制字符串。 | >>> f = 1.5 >>> f.hex() '0x1.8000000000000p+0' | |
float.imag | 返回复数的浮点型虚部数值。 | >>> f = 1.5-2.5j >>> f.imag -2.5 | |
float.is_integer() | 判断浮点型数字是否是整数。如果是则返回True,否则返回False | >>> f = 1.5 >>> f.is_integer() False >>> f = 2.0 >>> f.is_integer() True | |
float.mro() | |||
float.real | 返回复数的实部的数值。 | >>> f = 1.5 >>> f.real 1.5 >>> f = 1.5 + 2.4j >>> f.real 1.5 |
1.4、complex
以下是Python2.7的float内置函数:
序号 | 函数名 | 作用 |
complex.conjugate() | 返回复数的共轭复数。 | |
complex.imag | 返回复数的虚部数值。 | |
complex.mro() | ||
complex.real | 返回复数的实部数值。 |