跳轉到內容

Python 程式設計/數學

來自華夏公益教科書

有關基本的數學運算,包括加、減、乘、除等,請參見基本數學運算子章節。作為快速參考,內建的 Python 數學運算子包括加法 (+) 、減法 (-) 、乘法 (*) 、除法 (/) 、地板除 (//) 、模 (%) 和指數 (**) 。內建的 Python 數學函式包括舍入 (round()) 、絕對值 (abs()) 、最小值 (min()) 、最大值 (max()) 、帶餘數的除法 (divmod()) 和指數 (pow()) 。符號函式可以建立為 "sign = lambda n: 1 if n > 0 else -1 if n < 0 else 0"。

標準庫的 math 模組提供了一系列數學函式。

import math

v1 = math.sin(10)       # sine
v2 = math.cos(10)       # cosine
v3 = math.tan(10)       # tangent 

v4 = math.asin(10)      # arc sine
v5 = math.acos(10)      # arc cosine
v6 = math.atan(10)      # arc tangent

v7 = math.sinh(10)      # hyperbolic sine    
v8 = math.cosh(10)      # hyperbolic cosine
v9 = math.tanh(10)      # hyperbolic tangent

vA = math.pow(2, 4)     # 2 raised to 4
vB = math.exp(4)        # e ^ 4
vC = math.sqrt(10)      # square root
vD = math.pow(5, 1/3.0) # cubic root of 5
vE = math.log(3)        # ln; natural logarithm
vF = math.log(100, 10)  # base 10

vG = math.ceil(2.3)     # ceiling
vH = math.floor(2.7)    # floor

vI = math.pi
vJ = math.e

使用內建運算子的示例程式碼

[編輯 | 編輯原始碼]

此程式碼旨在複製計算器中的 log 函式

import time
base_number = input("[A]input base number: ")
new_number = 0
result = input("[end number]input result ")
exponent = 0

while int(new_number) != int(result):
    exponent += float("0.0000001")
    new_number = int(base_number)**float(exponent)
    print(new_number)
    
else:
    print("")
    print("The exponent or X is " + str(exponent))
    time.sleep(200)

cmath 模組提供了類似於 math 模組的函式,但適用於複數,還有其他一些函式。

偽隨機數生成器可從 random 模組獲得。

import random
v1 = random.random()     # Uniformly distributed random float >= 0.0 and < 1.0.
v2 = random.random()*10  # Uniformly distributed random float >= 0.0 and < 10.0
v3 = random.randint(0,9) # Uniformly distributed random int >= 0 and <=9
li=[1, 2, 3]; random.shuffle(li); print(li) # Randomly shuffled list

十進位制

[編輯 | 編輯原始碼]

decimal 模組支援十進位制浮點運算,避免了通常的浮點數的底層二進位制表示中某些對人類來說不直觀的缺陷。

import decimal
plainFloat = 1/3.0
v1 = plainFloat # 0.3333333333333333
decFloat = decimal.Decimal("0.33333333333333333333333333333333333333")
v2 = decFloat   # Decimal('0.33333333333333333333333333333333333333')
decFloat2 = decimal.Decimal(plainFloat)
v3 = decFloat2  # Decimal('0.333333333333333314829616256247390992939472198486328125')

fractions 模組透過 Fraction 類提供分數運算。與表示分數的浮點數相比,Fraction 分數不會丟失精度。

from fractions import Fraction
oneThird = Fraction(1, 3)
floatOneThird = 1/3.0
v1 = Fraction(0.25)                  # 1/4
v2 = Fraction(floatOneThird)         # 6004799503160661/18014398509481984
v3 = Fraction(1, 3) * Fraction(2, 5) # 2/15

statistics 模組從 Python 3.4 開始可用,提供了一些基本的統計函式。它只提供基本功能;它不能替代像 numpy 這樣的成熟的第三方庫。對於 Python 2.7,statistics 模組可以從 pypi 安裝。

import statistics as stats
v1 = stats.mean([1, 2, 3, 100]) # 26.5
v2 = stats.median([1, 2, 3, 100]) # 2.5
v3 = stats.mode([1, 1, 2, 3]) # 1
v4 = stats.pstdev([1, 1, 2, 3]) # 0.82915...; population standard deviation
v5 = stats.pvariance([1, 1, 2, 3]) # 0.6875; population variance
[編輯 | 編輯原始碼]
華夏公益教科書