Home  >  Article  >  Backend Development  >  python numeric types

python numeric types

巴扎黑
巴扎黑Original
2017-08-07 12:28:332258browse

The following editor will bring you a brief discussion of digital types and processing tools in Python. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look

Number type tools in python

Python provides a lot of advanced numerical programming for more advanced work Support and objects, including complete tools for numeric types:

1. Integers and floating point types,

2. Complex numbers,

3. Fixed-precision decimal numbers,

4. Rational fractions,

5. Sets,

6. Boolean type

7. Infinite integer precision

8. Various digital built-in functions and modules.

Basic number types

Python provides two basic types: integers (positive integers, negative integers) and floating point numbers (Note: Numbers with decimal parts), where in python we can use integers in multiple bases. And integers can be used with infinite precision.

The integer is expressed in decimal number string writing, and the floating point number is represented by a decimal point or scientific notation e. In the python2 version, integers are also divided into general integers (32 bits) and long integers (infinite precision). Long integers end with l. With python3, integers have only one form, with infinite precision.

Of course, integers in Python also appear in binary (0bxxxxxxxx), octal (0oxxxxxxxx), and hexadecimal (0x xxxxxxxx) forms.

Conversion between decimal numbers and other bases:


s=16
print(bin(s))
print(oct(s))
print(hex(s))

运行结果:
0b10000
0o20
0x10


print('{0:o},{1:x},{2:b}'.format(16,16,16))
print('%o,%x,%X'%(16,16,16))
运行结果:
20,10,10000
20,10,10

Conversion of other bases into decimal:


a=int('0b10000',2)
b=int('0o20',8)
c=int('0x10',16)
print(a)
print(b)
print(c)
运行结果:
16
16
16


print(eval('16'))
print(eval('0b10000'))
print(eval('0o20'))
print(eval('0x10'))
运行结果:
16
16
16
16

python expression operator

The expression is Mathematical symbols and operation symbols are written. The following table shows python expression operators and procedures:

##x&ybit and, set intersection##xf8544198a3556e828db2ffe050344174>y##x+y,x-yAddition, subtraction, merge and deletex*y,x%y,x/y,x//yMultiplication, remainder, division, floor division-x,+xUnary subtraction~xBitwise complement (reverse)x**yPower operationx[i]Index, function callx[i:j:k]Shardingx(...)Calling functionx.attrCalling attributes(...)Tuple, expression, generator[...]List, list parsing{...}Dictionary ,sets,sets and dictionary parsing

:操作符在python2和python3中略有不同,python2中不等于用!=或》a8093152e673feb7aba1828c43532094来表示,在python3中a8093152e673feb7aba1828c43532094方法被取消,不等于就用!=来表示。

x

在python2中可以使用混合类型,在python3中比较混合类型大小是会报错的,


python2
a = 1 > 'a'
print a
运行结果:
False


python3
a=1 > 'a' print(a) 运行结果: Traceback (most recent call last): File "C:/Users/jeff/PycharmProjects/python_file/practice/prac2.py", line 92, in a=1 > 'a' TypeError: unorderable types: int() > str()

上面的表格也是程序运行的优先级表格,自上而下,优先级越来越高,当然如果想要改变优先级,要是用括号来做。括号在python数字操作中经常会使用到,他不仅强制程序按照你想要的顺序运行,同时也增加了程序的可读性。

混合类型

这里指的是混合数字类型,比如整数和浮点数相加的结果是什么呢?

其实在python中首先将备操作对象转换成其中最复杂的操作对象的类型,然后再进行相同类型的对象进行数学运算。


print(1+0.2)

运行结果:
1.2

注:除此之外,在python中还存在着运算符重载功能比如‘+',除了做数字加法运算,在字符串拼接时也适用‘+'。

数字显示格式

由于一些硬件限制,数字显示有时看起来会很奇怪,例如:


在命令行中操作
>>>num = 1 / 3.0
>>>num
0.333333333333333333331
在pycharm中print操作
num = 1/3.0
print(num)
运行结果:
0.3333333333333333
num = 1/3.0
print('{0:4.2f}'.format(num))#4是前面空格格数,2是保留小数位
运行结果:
0.33

在命令行中显示的形式叫做默认的交互式回显,而print打印的叫做友好式回显,与reper和str的显示是一致的:


>>>num = 1/3.0
>>>repr(num)
0.333333333333333333331
>>>str(num)
0.3333333333333333

除法:传统除法,floor除法,真除法和截断除法

除法是python2与python3之间非常重要的一个变化。

一、除法操作符

python有两种除法操作符‘x/y'与‘x//y',其中‘/'在python2中是传统除法,即省略浮点数小数部分,然而显示整数,在python3中,除法就是真除法,即无论什么类型都会保留小数部分;‘//'也叫作floor除法,在python3中省略小数部分,剩下最小的能整除的整数部分,操作数如果是浮点数则结果显示浮点数,python2中整数截取整数,浮点数执行保留浮点数。

例:在python2中:

在python3中:

在python2中若是想要使用python3中的'/'则需要调用模块来完成,在python2中调用pision模块:

截断除法与floor除法一样都是取最接近整数向下取整,这使得在负数时也生效,即-2.5则为-3,而不是-2,想要得到真正的截取需要调用math模块:

python还支持复数的计算:

还支持compliex(real,imag)来创建复数。

更多复数计算参考模块cmath的参考手册。

位操作


x=1
print(x<<2)
print(x|2)
print(x&2)
print(x^2)
运行结果:
3
3

python3中使用bit_length查看二进制位数:


x=99
print(bin(x))
print(x.bit_length())
print(len(bin(x))-2)
运行结果:
0b1100011
7
7

内置数学工具

math模块


import math
print(math.pi)
print(math.e)
print(math.sin(110))
print(math.sqrt(144))
print(pow(2,3))
print(abs(-50))
print(sum((1,2,3)))
print(max(1,2,3))
print(min(1,2,3))
运行结果:
3.141592653589793
2.718281828459045
-0.044242678085070965
12.0
8
50
6
3
1

对于截取浮点数的操作有四种方式:


print(math.floor(2.577))
print(math.trunc(2.577))
print(round(2.577))
print(int(2.577))
运行结果:
2
2
3
2

random模块

获取随机数


import random
print(random.random())
print(random.randint(1,100))
运行结果:
0.9534845221467178
79

其他数字类型介绍

除了常见的整型与浮点数,还有一些其他较为常见的数字类型。

一、小数数字

虽然学习python有一段时间了,但是确实没有太明白浮点数与小数的区别,其实小数在某种程度上就是浮点数,只不过他有固定的位数和小数点,在python中有专门的模块导入小数,from decimal import Decimal。

注:浮点数缺乏精确性。


print(0.1+0.1+0.1-0.3)
输出结果:
5.551115123125783e-17

我想看到这里的兄弟可能已经慌了,然后使用python解释器试了一下,果然结果就是5.551115123125783e-17虽然很接近0,但是不是0。所以说浮点型本质是缺乏精确性。要精确就需要调用from decimal import Decimal。


from decimal import Decimal
print(Decimal('0.1')+Decimal('0.10')+Decimal('0.10')-Decimal('0.30'))
运行结果:
0.00

可以看出来小数相加也是自动升级为位数最多的。

注:浮点数创建小数对象,由于浮点数本身可能就不精确所以转换会产生较多的位数。


from decimal import Decimal
print(Decimal.from_float(1.88))
print(Decimal.from_float(1.25))
输出结果:
1.87999999999999989341858963598497211933135986328125
1.25

二、分数

分数类型与小数极为相似,他们都是通过固定小数位数和指定舍入或截取策略控制精度。分数使用Fraction模块导入。


from fractions import Fraction
x=Fraction(1,3)
y=Fraction(2,3)
print(x+y)
输出结果:
1

注:对于内存给定有限位数无法精确表示的值,浮点数的局限尤为明显。分数和小数都比浮点数更为准确。

三、集合

集合是无序元素组成,打印时顺序也是无序的,但是集合中没有重复的元素,所以我们常使用集合去重,尤其是在涉及数字和数据库的工作中。

我们有两个集合a与b:

a与b的交集为a.intersection(b)或者a & b。

a与b的差集为a.difference(b)或者a-b。

a与b的并集为a.union(b)或者a|b。

反向差集与对称差集(并集减去交集)为a.symmetric_difference(b)或者a^b。

合并为a.update(b),a.difference_update(b)求差集并赋值给a集合

删除元素可用discard(元素)或者remove(元素),pop()是随机删除一个元素,add插入一个项目。

注:set是可变数据类型,但是set里面的元素一定是不可变数据类型。


x={'a','c','b'}
y={'a','g','b'}
z={'a'}
print('a' in x)
print(x-y)
print(x|y)
print(x&y)
print(x^y)
print(z


x={'a','c','b'}
y={'a','g','b'}
z={'a'}
print(x.intersection(y))
print(x.union(y))
x.add('s')
print(x)
print(x.pop())
x.update({'w','e','o'})
print(x)
print(x)
运行结果:
{'a', 'b'}
{'c', 'a', 'b', 'g'}
{'a', 'b', 'c', 's'}
a
{'o', 'c', 's', 'w', 'b', 'e'}
{'o', 'c', 's', 'w', 'b', 'e'}

注:在python中{}是空字典,如果想要定义空集合要用set()。

集合要是添加列表等可变类型则会报错。


x={'a','c','b'}
l=[1,2,3]
x.add(l)
print(x)
运行结果:
Traceback (most recent call last):
 File "C:/Users/jeff/PycharmProjects/python_file/practice/prac2.py", line 111, in 
 print(x.add(l))
TypeError: unhashable type: 'list'

正确的添加序列方式为添加元组。


x={'a','c','b'}
l=(1,2,3)
x.add(l)
print(x)
运行结果:
{'c', 'b', 'a', (1, 2, 3)}

定义不可操作的集合使用frozenset定义集合。

字典解析:

与列表解析相类似,集合也是可迭代对象,所以可以使用for循环遍历。


x={1,2,3}
print({i ** 2 for i in x})
运行结果:
{1, 9, 4}

四、布尔值

python的一个数据类型,有两个值Ture 与 False。


print(type(True))
print(True == 1)
print(True is 1)
print(True + 1)
运行结果:

True
False
2

集合和bool值,还是比较常见的类型,在基础学习里也有涉及,在这里就不多写了。

python中的数字在程序编写时广泛使用,今后还会更深层次的学习python的扩展库。

Operator Description
yield Generator function sending protocol
lambda args:expression Generate anonymous function
x if y else z Ternary expression
x or y Logical OR (there is a short-circuit algorithm)
x and y Logical AND (there is a short-circuit algorithm)
not x Logical NOT
x in y , x not in y Member relationship
x is y ,x is not y Object entity test
x9ed41611d0522aeaf6f0eb242c851d8cy,x>=y,x==y,x!=y Compare sizes
x|y Bitwise OR, set union
x^y bit XOR, set symmetric difference
Shift left or right by y bits

The above is the detailed content of python numeric types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn