Python math函数

来自CloudWiki
跳转至: 导航搜索

官方文档

https://docs.python.org/zh-cn/3/library/math.html

常用用法

引入库:

import math

求开方

>>> math.sqrt(4) 2.0

>>> 4**0.5

2.0

取整

>>> math.ceil(3.5)

4

>>> math.floor(3.5)

3

>>> math.floor(3.5) 3

最大公约数

>>> math.gcd(12,16)

4

>>> math.lcm(12,16)

Traceback (most recent call last):
 File "<pyshell#9>", line 1, in <module>
   math.lcm(12,16)

AttributeError: module 'math' has no attribute 'lcm'

log函数

>>> math.log(2)

0.6931471805599453

>>> math.log(2,10)

0.30102999566398114

>>> math.log(10,100)

0.5

>>> math.log(100,10)

2.0

>>> math.log2(4)

2.0

三角函数

>>> a=math.pi/2

>>> math.sin(a)

1.0

>>> math.cos(a)

6.123233995736766e-17

>>> math.tan(a)

1.633123935319537e+16


求阶乘

>>> math.factorial(4)

24