Python数字类型及数学运算

1、数字类型分为int、float和complex,complex暂时用不到,int和float的相关运算和类型转换如下:

>>> 59+12
71
>>> 59-12
47
>>> 2*19
38
>>> 2**5
32
>>> 19/2
9.5
>>> 19//2
9
>>> 19%2
1
>>> 3*4.5-6 #自动类型转换
7.5
>>> x=4.5 #强制类型转换
>>> int(x)
4
>>> x='30'
>>> int(x)
30
>>> x='4.5'
>>> float(x)
4.5
>>> x='4.5' #转一次ok,想要自动转2次报错
>>> int(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '4.5'

 2、常量:

>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045

3、数学函数:

>>> import math
>>> math.ceil(4.5)
5
>>> math.floor(4.5)
4
>>> math.fabs(-4.5)
4.5
>>> math.fabs(10)
10.0
>>> max(3,100,301,200)#求最大值最小值
301
>>> min(3,100,301,200)
3
>>> math.factorial(2) #factorial,阶乘
2
>>> math.factorial(3)
6
>>> math.gcd(17,51)#返回能被两个参数整除的最大正整数
17
>>> math.gcd(256,128)
128
>>> math.ldexp(2,3)#已知尾数和指数的情况下,计算方程x=m*2^n
16.0
>>> math.frexp(16)#回退给定数值的尾数和指数,m介于0,1之间
(0.5, 5)
>>> math.frexp(15)
(0.9375, 4)
>>> math.exp(10)#x=e^n
22026.465794806718
>>> math.log(math.e)#默认一个参数,base=e
1.0
>>> math.log(16,2)#可输入两个参数,第二个参数是base
4.0
>>> math.log2(8)#以2为底的默认方法
3.0
>>> math.pow(3,4)#计算幂,转换成float
81.0
>>> math.sqrt(256)#开平方根
16.0
>>> x=math.pi #四舍五入
>>> x
3.141592653589793
>>> round(x,2)
3.14