指數
指數的計算,例如 3 的 5 次方,在 Python 裡可以用 3 ** 5,或是 pow(3, 5) 來表示。
In [1]: 3 ** 5 Out[1]: 243 In [2]: pow(3, 5) Out[2]: 243 In [3]: 2.7 ** 3 Out[3]: 19.683000000000003 In [4]: pow(2.7, 3) Out[4]: 19.683000000000003 In [5]: 3.2 ** 5.1 Out[5]: 376.93363218792746 In [6]: pow(3.2, 5.1) Out[6]: 376.93363218792746
比較特別的是,pow(1.0, x) 或 pow(x, 0.0) 結果都會是 1。即使 x = 0 也是如此。
In [1]: pow(1, 3) Out[1]: 1 In [2]: pow(1, 0) Out[2]: 1 In [3]: pow(1, -3) Out[3]: 1.0 In [4]: pow(1, 3.4) Out[4]: 1.0 In [5]: pow(3, 0) Out[5]: 1 In [6]: pow(3.2, 0) Out[6]: 1.0 In [7]: pow(-2.4, 0) Out[7]: 1.0 In [8]: pow(0, 0) Out[8]: 1 In [9]: pow(0, 3) Out[9]: 0 In [10]: pow(1.0, 3) Out[10]: 1.0
對數
對數的計算,可以用 log() 這個函數,使用 Python 裡的這個函數,必須先 import 一個叫做 math 的函式庫 (library)。如下,輸入:
In [1]: import math
就可以在接下來的程式中使用 math 裡的函數。
例如,要計算自然對數 log(12),就是以 e 為底數的對數,其中 e = 2.71828…。
In [2]: math.log(12) Out[2]: 2.4849066497880004
如果要計算以 10 為底數的對數,可以用 log10() 這個函數。如:
In [3]: math.log10(1000) Out[3]: 3.0
如果計算以其它數為底數的對數,可以用 log(x, base),由數學知識我們知道,它傳回的值會等於 log(x)/log(base),如:
In [5]: math.log(49, 7) Out[5]: 2.0 In [6]: math.log(2134, 9) Out[6]: 3.4888347376649085 In [7]: math.log(2134) / math.log(9) Out[7]: 3.4888347376649085
開平方根,可用 sqrt(x) 這個函數。它也會等於 x 的 0.5 次方。
In [3]: math.sqrt(16) Out[3]: 4.0 In [4]: pow(16, 0.5) Out[4]: 4.0 In [5]: 16 ** 0.5 Out[5]: 4.0
pow() 和 math.pow() 的異同
在 math 這個函式庫裡,也有一個指數函數 math.pow(x,y)
。用這個函數計算時,系統會將 x 和 y 都轉為浮點數計算。
In [2]: math.pow(3, 4) Out[2]: 81.0 In [3]: pow(3, 4) Out[3]: 81 In [4]: 3 ** 4 Out[4]: 81
在 pow(x, y) 中,如果 x 是負數,y 是正整數或負整數。會如何呢?
In [19]: pow(-3, 2) Out[19]: 9 In [20]: pow(-3, -2) Out[20]: 0.1111111111111111 In [21]: math.pow(-3, 2) Out[21]: 9.0 In [22]: math.pow(-3, -2) Out[22]: 0.1111111111111111 In [23]: pow(-3.2, 2) Out[23]: 10.240000000000002 In [24]: pow(-3.2, -2) Out[24]: 0.09765624999999999 In [25]: math.pow(-3.2, -2) Out[25]: 0.09765624999999999
然而,若 x 是負數,但是 y 不是整數時,會如何呢?這是用內建的 pow() 計算,仍會算出答案,而答案是個虛數。但是用 math.pow() 計算時,則會出現錯誤訊息。
In [29]: pow(-3.2, -2.1) Out[29]: (0.08267826817433492-0.026863797780267644j) In [30]: math.pow(-3.2, -2.1) Traceback (most recent call last): File "", line 1, in math.pow(-3.2, -2.1) ValueError: math domain error In [31]: pow(-1.0, 0.5) Out[31]: (6.123233995736766e-17+1j) In [32]: math.pow(-1.0, 0.5) Traceback (most recent call last): File "", line 1, in math.pow(-1.0, 0.5) ValueError: math domain error
在數學上,指數函數 f(x) = ax 的定義是 a > 0, 且 a ≠ 1,而 x 是實數。
在初學階段,我們先考慮符合指數函數定義的情形。
e 的 n 次方
自然底數 e 是理化上常用的常數,如要計算 e 的 n 次方,可以用 exp(n) 這個函數。
In [9]: math.exp(4) Out[9]: 54.598150033144236 In [10]: math.e ** 4 Out[10]: 54.59815003314423
在 Python 裡是以 math.e
來代表自然底數 e 這個常數。
In [11]: math.e Out[11]: 2.718281828459045
另一個常用的常數是圓周率 π,是以 math.pi
來表示。
In [2]: math.pi Out[2]: 3.141592653589793