不少數學運算依賴於一些特殊的常量。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庫限制。函數
浮點數計算可能致使兩種類型的異常值。第一種是inf(無窮大),當用double存儲一個浮點數,而該值會從一個具體很大絕對值的值上溢出時,就會出現這個異常值。 oop
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所用庫中的實現差別形成的。spa
使用無窮大值的除法運算未定義。將一個數除以無窮大值的結果是nan(不是一個數)。3d
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()。code
可使用isfinite()檢查其是普通的數仍是特殊值inf或nan。 orm
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。對象
涉及浮點值的比較容易出錯,每一步計算均可能因爲數值表示而引入偏差,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只接近它自身。
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。
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()相同的公式,取尾數和指數值做爲參數,並返回一個浮點數。
一個數的絕對值就是不帶正負號的本值。使用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與其餘值直接比較。
在二進制浮點數內存中表示精確度頗有難度。有些值沒法準確地表示,並且若是經過反覆計算來處理一個值,那麼計算越頻繁就越容易引人表示偏差。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。
指數生長曲線在經濟學、物理學和其餘科學中常常出現。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值很小時,若是單獨完成減法,則可能會損失精度。
儘管咱們天天討論角時更經常使用的是度,但弧度纔是科學和數學領域中度量角度的標準單位。弧度是在圓心相交的兩條線所構成的角,其終點落在圓的圓周上,終點之間相距一個弧度。
圓周長計算爲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 / π。
三角函數將三角形中的角與其邊長相關聯。在有周期性質的公式中常常出現三角函數,如諧波或圓周運動;在處理角時也會常常用到三角函數。標準庫中全部三角函數的角參數都被表示爲弧度。
給定一個直角三角形中的角,其正弦是對邊長度與斜邊長度之比(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。
雙曲函數常常出如今線性微分方程中,處理電磁場、流體力學、狹義相對論和其餘高級物理和數學問題時常會用到。
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()。
統計學中常常用到高斯偏差函數(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()實現即可以免可能的精度偏差。