python中math模塊常用函數介紹 取模(取餘)取絕對值 求階乘 求最大公約數最小公倍數 取對數 取根號 取冪(取次方) 取整函數 三角函數與反三角函數

前提:import math

兩個常用常量

     e = 2.718281828459045

     pi = 3.141592653589793

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

取模(取餘)

fmod(x,y)   返回x%y

例如:

>>> import math
>>> math.fmod(5,2)
1.0
>>> math.fmod(6,2)
0.0

取絕對值

fabs(x)   返回float x的絕對值。

例如:

>>> import math
>>> math.fabs(-1.25)
1.25
>>> math.fabs(5)
5.0

求階乘

factorial(x) 返回x!。如果x爲負數或非整數,則引發ValueError。

例如:

>>> import math
>>> math.factorial(5)
120
>>> math.factorial(-5)

Traceback (most recent call last):
  File "<pyshell#70>", line 1, in <module>
    math.factorial(-5)
ValueError: factorial() not defined for negative values
>>> math.factorial(5.1)

Traceback (most recent call last):
  File "<pyshell#71>", line 1, in <module>
    math.factorial(5.1)
ValueError: factorial() only accepts integral values

最大公約數與最小公倍數

gcd(x, y) 返回(x,y)的最大公約數。(注:gcd()不屬於math模塊,如要使用需要from fractions import gcd)

最小公倍數=(x*y)/gcd(x, y)

例如:

>>> from fractions import gcd
>>> gcd(6,9)
3
>>> gcd(50,60)
10
>>> 6*9/gcd(6,9)
18

求歐幾里得距離

hypot(x,y)   返回歐幾里德距離sqrt(x * x + y * y)

例如:

>>> import math
>>> math.hypot(3,4)
5.0
>>> math.hypot(5,10)
11.180339887498949

對數

log(x [,base])   將x的對數返回給定的基數。如果未指定基數,則返回x的自然對數(基數e)

log10(x)   返回x的基數10對數。

log1p(x)   返回1 + x(基數e)的自然對數。

exp(x)   返回自然對數e的x次方

expm1(x)   返回exp(x)-1。該函數避免了直接exp(x)-1所涉及的精度損失。

例如:

>>> import math
>>> math.log
<built-in function log>
>>> math.log(4,2)
2.0
>>> math.log(5)
1.6094379124341003
>>> math.log(5,math.e)
1.6094379124341003
>>> math.log10(100)
2.0
>>> math.log1p(5)
1.791759469228055
>>> math.log1p(4)
1.6094379124341003
>>> math.log(5)
1.6094379124341003
>>> math.exp(2)
7.38905609893065
>>> math.e**2
7.3890560989306495
>>> math.expm1(2)
6.38905609893065

取根號 取冪(取次方)

pow(x,y)   返回x ** y(xy次方)

pow(x,1.0/y)   返回對x開y次根號,即y次根號下的x的值。

sqrt(x)返回x的平方根。

例如:

>>> import math
>>> math.pow(2,3)
8.0
>>> math.pow(8,1.0/3)
2.0
>>> math.sqrt(4)
2.0

取整函數(點擊鏈接)

三角函數與反三角函數(點擊鏈接)

其他一些函數

copysign(x,y)  以y的符號返回x。

>>> math.copysign (2,-1)
-2.0

fsum(iterable)  返回迭代中的和值

>>> nums=[1,2,3,4,5,6,7,8,9]
>>> math.fsum (nums)
45.0

isinf(x) 檢查浮點數x是否爲無窮大,是返回True,否返回False

isnan(x) 檢查float x是否不是數字是返回True,否返回False

>>> inf=float('inf')
>>> math.isinf(inf)
True
>>> math.isinf(1.1)
False
>>> math.isnan(1)
False
>>> math.isnan(1.25)
False

其中 float('inf') 表示正無窮

-float('inf') 或 float('-inf') 表示負無窮

其中,inf 均可以寫成 Inf

ldexp(x,i)返回x *(2 ** i)

>>> math.ldexp (5,3)
40.0

modf(x)返回x的小數和整數部分。兩個結果都帶有x的符號並且是浮點數。

>>> math.modf(2.5)
(0.5, 2.0)
>>> math.modf(-2.5)
(-0.5, -2.0)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章