Python 常用的數學函數
Python 常用的數學函數列表
| 函數 | 描述 | 範例 | 
|---|---|---|
| math.sqrt(x) | 開平方根 | math.sqrt(16)→4.0 | 
| math.pow(x, y) | (x) 的 (y) 次方 | math.pow(2, 3)→8.0 | 
| math.sin(x) | 正弦函數 | math.sin(math.pi / 2)→1.0 | 
| math.cos(x) | 餘弦函數 | math.cos(math.pi)→-1.0 | 
| math.tan(x) | 正切函數 | math.tan(math.pi / 4)→1.0 | 
| math.asin(x) | 反正弦函數 | math.asin(1)→π/2 | 
| math.acos(x) | 反餘弦函數 | math.acos(1)→0.0 | 
| math.atan(x) | 反正切函數 | math.atan(1)→π/4 | 
| math.exp(x) | (e) 的 (x) 次方 | math.exp(1)→2.71828... | 
| math.log(x) | 自然對數(以 (e) 為底) | math.log(math.e)→1.0 | 
| math.log10(x) | 以 10 為底的對數 | math.log10(100)→2.0 | 
| math.factorial(x) | (x) 的階乘 | math.factorial(5)→120 | 
請注意,使用這些函數之前,需要在 Python 程式中引入 math 模組,即在程式的開頭加入 import math。
import math
之後就可以使用這些函數。例如,要計算 2 的 4 次方:
math.pow(2, 4)
16.0
圓周率 π 在這裡是用 math.pi 表示:
math.pi
3.141592653589793
自然對數的底數 e 是用 math.e 表示:
math.e
2.718281828459045
三角函數的計算時,要注意角度是要用弧度 (radian, rad) 計算,不是用度 (degree)。弧度的數學定義是:一個圓心角的弧度數等於該角所截取圓弧的長度與圓的半徑的比值。
一個半徑為 r 的圓形,圓心角為 180° 時,對應的圓弧長度是 π r。也就是說,180° 相等於弧度 π rad。
\(\frac{\pi}{2}rad = 90^\circ\)
\(\frac{\pi}{3}rad = 60^\circ\)
\(\frac{\pi}{4}rad = 45^\circ\)
\(\frac{\pi}{6}rad = 30^\circ\)
例如,要計算 sin(30°) 的值,必需要以 sin(π/6) 來計算,輸入:
math.sin(math.pi / 6)
0.49999999999999994
有趣的是,計算出來的答案不是 0.5,而是近似值。這是因為 Python 程式是以浮點數來做數值計算,所以產生的值可能是近似值。這在程式運算中時常會出現,使用者要留意可能產生的細微誤差。由這個例子,也可以看出電腦和人腦的差別。
若要在弧度和度之間轉換,math 模組也提供了兩個函數方便轉換 radians() 和 degrees()。
# 將度轉為弧度
degrees = 90
radians = math.radians(degrees)
print(degrees, "度", "等於",  radians, "弧度")
90 度 等於 1.5707963267948966 弧度
# 將弧度轉換為度
radians = 1.5
degrees = math.degrees(radians)
print(radians, "弧度", "等於", degrees, "度")
1.5 弧度 等於 85.94366926962348 度
現在,您也可以試著用這些數學函數來做常見的計算了。