Python模块学习:引入math模块及库函数大全

Python的math模块为我们提供了一系列关于数学方面的功能,可以帮助我们进行指数、对数、平方根、三角函数等运算。

1. 冥和对数

我们在求某个数的平方根或者是平方和又或者是幂运算的时候,往往要借助math模块。

取对数运算:math.log(x[,底数]),这种方式会返回一个以基数为底的x的对数,如果省略底数就是以2为底。

例如:

12345 import math = math.log( 144 , 12 ) = math.log( 36 , 6 ) print (a) print (b)

输出结果为:

12 2.0 2.0

取平方根运算:math.sqrt(x),返回x的平方根。

例如:

12345 import math = math.sqrt( 16 ) = math.sqrt( 256 ) print (a) print (b)

输出结果为:

12 4.0 16.0

取幂运算:pow(x,y),返回的是x的y次幂。

例如:

12345 import math = math. pow ( 2 , 4 ) = math. pow ( 10 , 3 ) print (a) print (b)

输出结果为:

12 16.0 1000.0

2. 三角函数

三角函数的使用和上面的用法类似。

三角正弦值:math.sin(x)

三角余弦值:math.cos(x)

三角正切值:math.tan(x)

弧度的反正弦:math.asin(x)

弧度的反余弦:math.acos(x)

弧度的反正切:math.atan(x)

如果是将弧度转换为角度或者将角度转换为弧度,采用下面的用法。

弧度转角度:math.degress(x)

角度转弧度:math.radinans(x)

看下面的例子:

1234567891011121314151617 import math = math.sin( 30 ) = math.cos( 30 ) = math.tan( 30 ) = math.asin( 0.6 ) = math.acos( 0.6 ) = math.atan( 0.6 ) = math.degrees( 2 * math.pi) = math.radians( 360 / math.pi) print (a) print (b) print (c) print (d) print (e) print (f) print (g) print (h)

输出结果为:

12345678 - 0.9880316240928618 0.15425144988758405 - 6.405331196646276 0.6435011087932844 0.9272952180016123 0.5404195002705842 360.0 2.0

需要注意的是我们在Python里使用math.pi来表示‘π’。

  3. 舍入函数

math模块中还提供了几个函数帮助我们进行舍入操作。

math.ceil(x):返回大于x或等于x的最小整数。

math.floor(x):返回小于x或等于x的最大整数。

同时在Python中有一个内置函数round(x)为我们提供四舍五入的操作。

代码如下:

123456789 import math = math.ceil( 3.5 ) = math.floor( 3.5 ) = round ( 3.5 ) = round ( 3.4 ) print (a) print (b) print (c) print (d)

输出结果为:

1234 4 3 4 3

4. 总结

本节中主要为大家讲述了Python中math模块的用法,需要注意的是math模块中的函数只适用于整数和浮点数,如果是复数的话我们要采用cmath模块,在这里就不作过多的介绍,math模块是系统内置的模块,在设计到数学运算的时候我们可以直接进行引入并使用。