1. math數學函數
1.1 特殊常量
很多數學運算依賴於一些特殊的常量。math包含有π(pi)、e、nan(不是一個數)和infinity(無窮大)的值。
import math print(' π: {:.30f}'.format(math.pi)) print(' e: {:.30f}'.format(math.e)) print('nan: {:.30f}'.format(math.nan)) print('inf: {:.30f}'.format(math.inf))
π和e的精度僅受平台的浮點數C庫限制。
1.2 測試異常值
浮點數計算可能導致兩種類型的異常值。第一種是inf(無窮大),當用double存儲一個浮點數,而該值會從一個具體很大絕對值的值上溢出時,就會出現這個異常值。
import math print('{:^3} {:6} {:6} {:6}'.format( 'e', 'x', 'x**2', 'isinf')) print('{:-^3} {:-^6} {:-^6} {:-^6}'.format( '', '', '', '')) for e in range(0, 201, 20): x = 10.0 ** e y = x * x print('{:3d} {:<6g} {:<6g} {!s:6}'.format( e, x, y, math.isinf(y), ))
當這個例子中的指數變得足夠大時,x的平方無法再存放一個double中,這個值就會被記錄為無窮大。
不過,並不是所有浮點數溢出都會導致inf值。具體地,用浮點值計算一個指數時,會產生OverflowError而不是保留inf結果。
x = 10.0 ** 200 print('x =', x) print('x*x =', x * x) print('x**2 =', end=' ') try: print(x ** 2) except OverflowError as err: print(err)
這種差異是由C和Python所用庫中的實現差異造成的。
使用無窮大值的除法運算未定義。將一個數除以無窮大值的結果是nan(不是一個數)。
import math x = (10.0 ** 200) * (10.0 ** 200) y = x / x print('x =', x) print('isnan(x) =', math.isnan(x)) print('y = x / x =', x / x) print('y == nan =', y == float('nan')) print('isnan(y) =', math.isnan(y))
nan不等於任何值,甚至不等於其自身,所以要想檢查nan,需要使用isnan()。
可以使用isfinite()檢查其是普通的數還是特殊值inf或nan。
import math for f in [0.0, 1.0, math.pi, math.e, math.inf, math.nan]: print('{:5.2f} {!s}'.format(f, math.isfinite(f)))
如果是特殊值inf或nan,則isfinite()返回false,否則返回true。
1.3 比較
涉及浮點值的比較容易出錯,每一步計算都可能由於數值表示而引入誤差,isclose()函數使用一種穩定的算法來盡可能減少這些誤差,同時完成相對和絕對比較。所用的公式等價於:
abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol)
默認地,isclose()會完成相對比較,容差被設置為le-09,這表示兩個值之差必須小於或等於le乘以a和b中較大的絕對值。向isclose()傳入關鍵字參數rel_tol可以改變這個容差。在這個例子中,值之間的差距必須在10%以內。
import math INPUTS = [ (1000, 900, 0.1), (100, 90, 0.1), (10, 9, 0.1), (1, 0.9, 0.1), (0.1, 0.09, 0.1), ] print('{:^8} {:^8} {:^8} {:^8} {:^8} {:^8}'.format( 'a', 'b', 'rel_tol', 'abs(a-b)', 'tolerance', 'close') ) print('{:-^8} {:-^8} {:-^8} {:-^8} {:-^8} {:-^8}'.format( '-', '-', '-', '-', '-', '-'), ) fmt = '{:8.2f} {:8.2f} {:8.2f} {:8.2f} {:8.2f} {!s:>8}' for a, b, rel_tol in INPUTS: close = math.isclose(a, b, rel_tol=rel_tol) tolerance = rel_tol * max(abs(a), abs(b)) abs_diff = abs(a - b) print(fmt.format(a, b, rel_tol, abs_diff, tolerance, close))
0.1和0.09之間的比較失敗,因為誤差表示0.1。
要使用一個固定或“絕對”容差,可以傳入abs_tol而不是rel_tol。
import math INPUTS = [ (1.0, 1.0 + 1e-07, 1e-08), (1.0, 1.0 + 1e-08, 1e-08), (1.0, 1.0 + 1e-09, 1e-08), ] print('{:^8} {:^11} {:^8} {:^10} {:^8}'.format( 'a', 'b', 'abs_tol', 'abs(a-b)', 'close') ) print('{:-^8} {:-^11} {:-^8} {:-^10} {:-^8}'.format( '-', '-', '-', '-', '-'), ) for a, b, abs_tol in INPUTS: close = math.isclose(a, b, abs_tol=abs_tol) abs_diff = abs(a - b) print('{:8.2f} {:11} {:8} {:0.9f} {!s:>8}'.format( a, b, abs_tol, abs_diff, close))
對於絕對容差,輸入值之差必須小於給定的容差。
nan和inf是特殊情況。
import math print('nan, nan:', math.isclose(math.nan, math.nan)) print('nan, 1.0:', math.isclose(math.nan, 1.0)) print('inf, inf:', math.isclose(math.inf, math.inf)) print('inf, 1.0:', math.isclose(math.inf, 1.0))
nan不接近任何值,包括它自身。inf只接近它自身。
1.4 將浮點值轉換為整數
math模塊中有3個函數用於將浮點值轉換為整數。這3個函數分別采用不同的方法,並適用於不同的場合。
最簡單的是trunc(),其會截斷小數點后的數字,只留下構成這個值整數部分的有效數字。floor()將其輸入轉換為不大於它的最大整數,ceil()(上限)會生成按順序排在這個輸入值之后的最小整數。
import math HEADINGS = ('i', 'int', 'trunk', 'floor', 'ceil') print('{:^5} {:^5} {:^5} {:^5} {:^5}'.format(*HEADINGS)) print('{:-^5} {:-^5} {:-^5} {:-^5} {:-^5}'.format( '', '', '', '', '', )) fmt = '{:5.1f} {:5.1f} {:5.1f} {:5.1f} {:5.1f}' TEST_VALUES = [ -1.5, -0.8, -0.5, -0.2, 0, 0.2, 0.5, 0.8, 1, ] for i in TEST_VALUES: print(fmt.format( i, int(i), math.trunc(i), math.floor(i), math.ceil(i), ))
trunc()等價於直接轉換為int。
1.5 浮點值的其他表示
modf()取一個浮點數,並返回一個元組,其中包含這個輸入值的小數和整數部分。
import math for i in range(6): print('{}/2 = {}'.format(i, math.modf(i / 2.0)))
返回值中的兩個數字均為浮點數。
frexp()返回一個浮點數的尾數和指數,可以用這個函數創建值的一種更可移植的表示。
import math print('{:^7} {:^7} {:^7}'.format('x', 'm', 'e')) print('{:-^7} {:-^7} {:-^7}'.format('', '', '')) for x in [0.1, 0.5, 4.0]: m, e = math.frexp(x) print('{:7.2f} {:7.2f} {:7d}'.format(x, m, e))
frexp()使用公式x = m * 2**e,並返回值m和e。
ldexp()與frexp()正好相反。
import math print('{:^7} {:^7} {:^7}'.format('m', 'e', 'x')) print('{:-^7} {:-^7} {:-^7}'.format('', '', '')) INPUTS = [ (0.8, -3), (0.5, 0), (0.5, 3), ] for m, e in INPUTS: x = math.ldexp(m, e) print('{:7.2f} {:7d} {:7.2f}'.format(m, e, x))
ldexp()使用與frexp()相同的公式,取尾數和指數值作為參數,並返回一個浮點數。
1.6 正號和負號
一個數的絕對值就是不帶正負號的本值。使用fabs()可以計算一個浮點數的絕對值。
import math print(math.fabs(-1.1)) print(math.fabs(-0.0)) print(math.fabs(0.0)) print(math.fabs(1.1))
在實際中,float的絕對值表示為一個正值。
要確定一個值的符號,以便為一組值指定相同的符號或者比較兩個值,可以使用copysign()來設置正確值的符號。
import math HEADINGS = ('f', 's', '< 0', '> 0', '= 0') print('{:^5} {:^5} {:^5} {:^5} {:^5}'.format(*HEADINGS)) print('{:-^5} {:-^5} {:-^5} {:-^5} {:-^5}'.format( '', '', '', '', '', )) VALUES = [ -1.0, 0.0, 1.0, float('-inf'), float('inf'), float('-nan'), float('nan'), ] for f in VALUES: s = int(math.copysign(1, f)) print('{:5.1f} {:5d} {!s:5} {!s:5} {!s:5}'.format( f, s, f < 0, f > 0, f == 0, ))
還需要另一個類似copysign()的函數,因為不能將nan和-nan與其他值直接比較。
1.7 常用計算
在二進制浮點數內存中表示精確度很有難度。有些值無法准確地表示,而且如果通過反復計算來處理一個值,那么計算越頻繁就越容易引人表示誤差。math包含一個函數來計算一系列浮點數的和,它使用一種高效的算法來盡量減少這種誤差。
import math values = [0.1] * 10 print('Input values:', values) print('sum() : {:.20f}'.format(sum(values))) s = 0.0 for i in values: s += i print('for-loop : {:.20f}'.format(s)) print('math.fsum() : {:.20f}'.format(math.fsum(values)))
給定一個包含10個值的序列,每個值都等於0.1,這個序列總和的期望值為1.0。不過,由於0.1不能精確地表示為一個浮點數,所以會在總和中引入誤差,除非用fsum()來計算。
factorial()常用於計算一系列對象的排列和組合數。一個正整數n的階乘(表示為n!)被遞歸的定義為(n-1)!*n,並在0!==1停止遞歸。
import math for i in [0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.1]: try: print('{:2.0f} {:6.0f}'.format(i, math.factorial(i))) except ValueError as err: print('Error computing factorial({}): {}'.format(i, err))
factorial()只能處理整數,不過它確實也接受float參數,只要這個參數可以轉換為一個整數而不丟值。
gamma()類似於factorial(),不過它可以處理實數,而且值會下移一個數(gamma等於(n - 1)!)。
import math for i in [0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]: try: print('{:2.1f} {:6.2f}'.format(i, math.gamma(i))) except ValueError as err: print('Error computing gamma({}): {}'.format(i, err))
由於0會導致開始值為負,所以這是不允許的。
lgamma()會返回對輸入值求gamma所得結果的絕對值的自然對數。
import math for i in [0, 1.1, 2.2, 3.3, 4.4, 5.5, 6.6]: try: print('{:2.1f} {:.20f} {:.20f}'.format( i, math.lgamma(i), math.log(math.gamma(i)), )) except ValueError as err: print('Error computing lgamma({}): {}'.format(i, err))
使用lgamma()會比使用gamma()結果單獨計算對數更精確。
求模操作符(%)會計算一個除法表達式的余數(例如,5 % 2 = 1)。Python語言內置的這個操作符可以很好地處理整數,但是與很多其他浮點數運算類似,中間計算可能帶來表示問題,從而進一步造成數據丟失。fmod()可以為浮點值提供一個更精確的實現。
import math print('{:^4} {:^4} {:^5} {:^5}'.format( 'x', 'y', '%', 'fmod')) print('{:-^4} {:-^4} {:-^5} {:-^5}'.format( '-', '-', '-', '-')) INPUTS = [ (5, 2), (5, -2), (-5, 2), ] for x, y in INPUTS: print('{:4.1f} {:4.1f} {:5.2f} {:5.2f}'.format( x, y, x % y, math.fmod(x, y), ))
還有一點可能經常產生混淆,即fmod()計算模所使用的算法與%使用的算法也有所不同,所以結果的符號不同。
可以使用gcd()找出兩個整數公約數中最大的整數——也就是最大公約數。
import math print(math.gcd(10, 8)) print(math.gcd(10, 0)) print(math.gcd(50, 225)) print(math.gcd(11, 9)) print(math.gcd(0, 0))
如果兩個值都為0,則結果為0。
1.8 指數和對數
指數生長曲線在經濟學、物理學和其他科學中經常出現。Python有一個內置的冪運算符(“**”),不過,如果需要將一個可調用函數作為另一個函數的參數,那么可能需要用到pow()。
import math INPUTS = [ # Typical uses (2, 3), (2.1, 3.2), # Always 1 (1.0, 5), (2.0, 0), # Not-a-number (2, float('nan')), # Roots (9.0, 0.5), (27.0, 1.0 / 3), ] for x, y in INPUTS: print('{:5.1f} ** {:5.3f} = {:6.3f}'.format( x, y, math.pow(x, y)))
1的任何次冪總返回1.0,同樣,任何值的指數為0.0時也總是返回1.0.對於nan值(不是一個數),大多數運算都返回nan。如果指數小於1,pow()會計算一個根。
由於平方根(指數為1/2)被使用的非常頻繁,所以有一個單獨的函數來計算平方根。
import math print(math.sqrt(9.0)) print(math.sqrt(3)) try: print(math.sqrt(-1)) except ValueError as err: print('Cannot compute sqrt(-1):', err)
計算負數的平方根需要用到復數,這不在math的處理范圍內。試圖計算一個負值的平方根時,會導致一個ValueError。
對數函數查找滿足條件x=b**y的y。默認log()計算自然對數(底數為e)。如果提供了第二個參數,則使用這個參數值作為底數。
import math print(math.log(8)) print(math.log(8, 2)) print(math.log(0.5, 2))
x小於1時,求對數會產生負數結果。
log()有三個變形。在給定浮點數表示和取整誤差的情況下,由log(x,b)生成的計算值只有有限的精度(特別是對於某些底數)。log10()完成log(x,10)計算,但是會使用一種比log()更精確的算法。
import math print('{:2} {:^12} {:^10} {:^20} {:8}'.format( 'i', 'x', 'accurate', 'inaccurate', 'mismatch', )) print('{:-^2} {:-^12} {:-^10} {:-^20} {:-^8}'.format( '', '', '', '', '', )) for i in range(0, 10): x = math.pow(10, i) accurate = math.log10(x) inaccurate = math.log(x, 10) match = '' if int(inaccurate) == i else '*' print('{:2d} {:12.1f} {:10.8f} {:20.18f} {:^5}'.format( i, x, accurate, inaccurate, match, ))
輸出中末尾有*的行突出強調了不精確的值。
類似於log10(),log2()會完成等價於math.log(x,2)的計算。
import math print('{:>2} {:^5} {:^5}'.format( 'i', 'x', 'log2', )) print('{:-^2} {:-^5} {:-^5}'.format( '', '', '', )) for i in range(0, 10): x = math.pow(2, i) result = math.log2(x) print('{:2d} {:5.1f} {:5.1f}'.format( i, x, result, ))
取決於底層平台,這個內置的特殊用途函數能提供更好的性能和精度,因為它利用了針對底數2的特殊用途算法,而在更一般用途的函數中沒有使用這些算法。
log1p()會計算Newton-Mercator序列(1+x的自然對數)。
import math x = 0.0000000000000000000000001 print('x :', x) print('1 + x :', 1 + x) print('log(1+x):', math.log(1 + x)) print('log1p(x):', math.log1p(x))
對於非常接近於0的x,log1p()會更為精確,因為它使用的算法可以補償由初識加法帶來的取整誤差。
exp()會計算指數函數(e**x)。
import math x = 2 fmt = '{:.20f}' print(fmt.format(math.e ** 2)) print(fmt.format(math.pow(math.e, 2))) print(fmt.format(math.exp(2)))
類似於其他特殊函數,與等價的通用函數math.pow(math.e,x)相比,exp()使用的算法可以生成更精確的結果。
expm1()是log1p()的逆運算,會計算e**x-1。
import math x = 0.0000000000000000000000001 print(x) print(math.exp(x) - 1) print(math.expm1(x))
類似於log1p(),x值很小時,如果單獨完成減法,則可能會損失精度。
1.9 角
盡管我們每天討論角時更常用的是度,但弧度才是科學和數學領域中度量角度的標准單位。弧度是在圓心相交的兩條線所構成的角,其終點落在圓的圓周上,終點之間相距一個弧度。
圓周長計算為2πr,所以弧度與π(這是三角函數計算中經常出現的一個值)之間存在一個關系。這個關系使得三角學和微積分中都使用了弧度,因為利用弧度可以得到更緊湊的公式。
要把度轉換為弧度,可以使用redians()。
import math print('{:^7} {:^7} {:^7}'.format( 'Degrees', 'Radians', 'Expected')) print('{:-^7} {:-^7} {:-^7}'.format( '', '', '')) INPUTS = [ (0, 0), (30, math.pi / 6), (45, math.pi / 4), (60, math.pi / 3), (90, math.pi / 2), (180, math.pi), (270, 3 / 2.0 * math.pi), (360, 2 * math.pi), ] for deg, expected in INPUTS: print('{:7d} {:7.2f} {:7.2f}'.format( deg, math.radians(deg), expected, ))
轉換公式為rad = deg * π / 180。
要從弧度轉換為度,可以使用degrees()。
import math INPUTS = [ (0, 0), (math.pi / 6, 30), (math.pi / 4, 45), (math.pi / 3, 60), (math.pi / 2, 90), (math.pi, 180), (3 * math.pi / 2, 270), (2 * math.pi, 360), ] print('{:^8} {:^8} {:^8}'.format( 'Radians', 'Degrees', 'Expected')) print('{:-^8} {:-^8} {:-^8}'.format('', '', '')) for rad, expected in INPUTS: print('{:8.2f} {:8.2f} {:8.2f}'.format( rad, math.degrees(rad), expected, ))
具體轉換公式為deg = rad * 180 / π。
1.10 三角函數
三角函數將三角形中的角與其邊長相關聯。在有周期性質的公式中經常出現三角函數,如諧波或圓周運動;在處理角時也會經常用到三角函數。標准庫中所有三角函數的角參數都被表示為弧度。
給定一個直角三角形中的角,其正弦是對邊長度與斜邊長度之比(sin A = 對邊/斜邊)。余弦是鄰邊長度與斜邊長度之比(cos A = 鄰邊/斜邊)。正切是對邊與鄰邊之比(tan A = 對邊/鄰邊)。
import math print('{:^7} {:^7} {:^7} {:^7} {:^7}'.format( 'Degrees', 'Radians', 'Sine', 'Cosine', 'Tangent')) print('{:-^7} {:-^7} {:-^7} {:-^7} {:-^7}'.format( '-', '-', '-', '-', '-')) fmt = '{:7.2f} {:7.2f} {:7.2f} {:7.2f} {:7.2f}' for deg in range(0, 361, 30): rad = math.radians(deg) if deg in (90, 270): t = float('inf') else: t = math.tan(rad) print(fmt.format(deg, rad, math.sin(rad), math.cos(rad), t))
正切也可以被定義為角的正弦值與其余弦值之比,因為弧度π/2和3π/2的余弦是0,所以相應的正切值為無窮大。
給定一個點(x,y),點[(0,0),(x,0),(x,y)]構成的三角形中斜邊長度為(x**2+y**2)**1/2,可以用hypot()來計算。
import math print('{:^7} {:^7} {:^10}'.format('X', 'Y', 'Hypotenuse')) print('{:-^7} {:-^7} {:-^10}'.format('', '', '')) POINTS = [ # simple points (1, 1), (-1, -1), (math.sqrt(2), math.sqrt(2)), (3, 4), # 3-4-5 triangle # on the circle (math.sqrt(2) / 2, math.sqrt(2) / 2), # pi/4 rads (0.5, math.sqrt(3) / 2), # pi/3 rads ] for x, y in POINTS: h = math.hypot(x, y) print('{:7.2f} {:7.2f} {:7.2f}'.format(x, y, h))
對於圓上的點,其斜邊總是等於1。
還可以用這個函數查看兩個點之間的距離。
import math print('{:^8} {:^8} {:^8} {:^8} {:^8}'.format( 'X1', 'Y1', 'X2', 'Y2', 'Distance', )) print('{:-^8} {:-^8} {:-^8} {:-^8} {:-^8}'.format( '', '', '', '', '', )) POINTS = [ ((5, 5), (6, 6)), ((-6, -6), (-5, -5)), ((0, 0), (3, 4)), # 3-4-5 triangle ((-1, -1), (2, 3)), # 3-4-5 triangle ] for (x1, y1), (x2, y2) in POINTS: x = x1 - x2 y = y1 - y2 h = math.hypot(x, y) print('{:8.2f} {:8.2f} {:8.2f} {:8.2f} {:8.2f}'.format( x1, y1, x2, y2, h, ))
使用x值之差和y值之差將一個端點移至原點,然后將結果傳入hypot()。
math還定義了反三角函數。
import math for r in [0, 0.5, 1]: print('arcsine({:.1f}) = {:5.2f}'.format(r, math.asin(r))) print('arccosine({:.1f}) = {:5.2f}'.format(r, math.acos(r))) print('arctangent({:.1f}) = {:5.2f}'.format(r, math.atan(r))) print()
1.57大約對於π/2,或90度,這個角的正弦為1,余弦為0。
1.11 雙曲函數
雙曲函數經常出現在線性微分方程中,處理電磁場、流體力學、狹義相對論和其他高級物理和數學問題時常會用到。
import math print('{:^6} {:^6} {:^6} {:^6}'.format( 'X', 'sinh', 'cosh', 'tanh', )) print('{:-^6} {:-^6} {:-^6} {:-^6}'.format('', '', '', '')) fmt = '{:6.4f} {:6.4f} {:6.4f} {:6.4f}' for i in range(0, 11, 2): x = i / 10.0 print(fmt.format( x, math.sinh(x), math.cosh(x), math.tanh(x), ))
余弦函數和正弦函數構成一個圓,而雙曲余弦函數和雙曲正弦函數構成半個雙曲線。
另外還提供了反雙曲函數acosh()、asinh()和atanh()。
1.12 特殊函數
統計學中經常用到高斯誤差函數(Gauss error function)。
import math print('{:^5} {:7}'.format('x', 'erf(x)')) print('{:-^5} {:-^7}'.format('', '')) for x in [-3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3]: print('{:5.2f} {:7.4f}'.format(x, math.erf(x)))
對於誤差函數,erf(-x) == -erf(x)。
補余誤差函數erfc()生成等價於1 - erf(x)的值。
import math print('{:^5} {:7}'.format('x', 'erfc(x)')) print('{:-^5} {:-^7}'.format('', '')) for x in [-3, -2, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 2, 3]: print('{:5.2f} {:7.4f}'.format(x, math.erfc(x)))
如果x值很小,那么在從1做減法時erfc()實現便可以避免可能的精度誤差。