Python核心数据类型之数字类型及其运算
数字类型
Python的数字字面量:
布尔型,(长)整数,浮点数,复数;
True: 1,False:0
数字运算:
x + y, x - y,x ** y(幂运算)
x * y, x / y, x // y(截断除法),
x % y(取模 x mod y)
-x(一元减法), +x(一元加法)
位运算:
x | y(按位或), x & y(按位与), x ^ y(按位异或), ~x(按位求反)
x << y(左移), x >> y(右移)
内置算数模块:importmath
例1:数字型位移运算
In [1]: num=2
In [2]: num <<3
Out[2]: 16
In [3]: num1=81
In [4]: num1>>3
Out[4]: 10
In [5]: num2=16
In [6]: num2>>3
Out[6]: 2
例2:数字型按位运算
In [7]: True & False
Out[7]: False
In [8]: True | False
Out[8]: True
In [9]: 255 &101
Out[9]: 101
In [10]: 255 |101
Out[10]: 255
In [11]: 255 ^ 101
Out[11]: 154
In [15]: ~101
Out[15]: -102
In [16]: ~-102
Out[16]: 101
例3:数字型幂运算
In [17]: 2**3
Out[17]: 8
In [18]: (1-0.01)**365
Out[18]: 0.025517964452291125
In [19]: (1+0.01)**365
Out[19]: 37.78343433288728
例4:数字类型内置算数模块
In [39]: import math
In [40]: math.
math.acos math.cos math.factorial math.ldexp math.sin
math.acosh math.cosh math.floor math.lgamma math.sinh
math.asin math.degrees math.fmod math.log math.sqrt
math.asinh math.e math.frexp math.log10 math.tan
math.atan math.erf math.fsum math.log1p math.tanh
math.atan2 math.erfc math.gamma math.modf math.trunc
math.atanh math.exp math.hypot math.pi
math.ceil math.expm1 math.isinf math.pow
math.copysign math.fabs math.isnan math.radians
In [40]: math.pi
Out[40]: 3.141592653589793
In [41]: num=4
In [42]: math.cos(num)
Out[42]: -0.6536436208636119
In [43]: math.sqrt(num)
Out[43]: 2.0