Python 全攻略 - Math and Random Module

Math and Random Module

Math Module

  • math.pi, math.e (兩個無理數的常數)
  • math.inf → floating-point infinity (代表無限大的浮點數)
  • math.ceil → Ceiling 的定義: 大於等於 某實數 x 的最小整數
  • math.floor → Floor 的定義: 小於等於 某實數 x 的最大整數 精度與負數的探討
    • floor(3.14) → 3
    • floor(1.9999) → 1
    • floor(2) → 2
    • floor(-3.1) → -4 (for negative number, floor is not quite the sams as truncation!)
  • math.isnan(x) → NaN: stands for not a number (數字 Return False,非數字則 Return True)
  • Trigonometric functions(三角函數), sin(), cos() and tan()
  • Angular conversion(弧度與角度的換算), degrees() and radians()
  • Hyperbolic functions(雙曲線), sinh(), cosh() and tanh()
  • Number-theoretic functions(數論 - 與整數有關的數學) → lcm(), gcd(), and remainder()
import math

print(100000000000 < math.inf)
print("_" * 50)
print(math.isnan(56))
print(math.isnan(math.inf))
print(math.isnan(float('nan'))) # True

print("_" * 50)

print(2**3) # 2 的 3 次方 -> int
print(pow(2, 3)) # built-in pow() -> int
print(math.pow(2, 3)) # math module, 計算前會先把兩個 arguments 轉成 float
True
__________________________________________________
False
False
True
__________________________________________________
8
8
8.0
import math

print(math.log(10))  # 未指定第二個 argument,預設為以 e 為底 -> e = 2.71828182845904
print(math.log(10, 10))  # 以 10 為底
print(math.log(10, 2))  # 以 2 為底

print("_" * 50)

print(math.radians(180)) # 得到 Pi
print(math.radians(180) == math.pi )
print(math.radians(90)) # 得到 -> 二分之 Pi
print(math.degrees(6)) # 角度
2.302585092994046
1.0
3.3219280948873626
__________________________________________________
3.141592653589793
True
1.5707963267948966
343.77467707849394

Random Module Part I

  • Python implements pseudo-random number generators(PRNG) for various distributions
    • random.random() → range [0.0, 1.0]
    • random.randrange(start, stop[, step]) → start(int - inclusive),stop(int - exclusive)
    • random.randint(a, b) - return a random interger N (a<=N<=b), Alais of randrange(a, b+1)
import random

for n in range(2):
    print(random.random()) # 從 0.0 ~ 0.999999999999 中,亂數取出一數值
0.28361821790671515
0.674964847134956
import random

for i in range(3):
    print(random.randrange(10, 21)) # 10 ~ 20,但不包含 21, Equivalent to randint(10, 20)
17
12
20
import random

for i in range(3):
    print(random.randint(10, 20)) # 10 ~ 20 間的整數,包含 20
14
20
15

Random Module Part II

  • seed() → save the state of a random function (Make the randomly chosen data consistent)
  • this function is helpful for testing codes or doing machine learning

  • random.choice(seq) →
    • sequence: String, List and Tuple
    • returns a random element from the non-empty sequence
    • raises IndexError if seq is empty
  • random.choices(sequence, weights=None, cum_weights=None, k=1)
    • returns k sized list of elements chosen from the sequence
    • weight, cum_weight(accumulated) → 二擇一
    • raises IndexError if seq is empty
  • random.sample(sequence, k)
    • return a k length list of unique elements chosen from the population sequence
    • used for random sampling without replacement
    • k cannot be negative or bigger than the size of the sequence
  • random.shuffle(x)
    • permanently shuffle the sequence x in place. (Sequence x has to be mutable)
    • use sample(x,k=len(x)) to shuffle an immutable sequence. (return a new shuffled list)
import random

random.seed(10) # 固定所取出的十個 element,不論跑幾次都不變

for i in range(10):
    print(random.randint(1, 1000))

586
34
440
495
592
16
212
474
833
504
import random

sentence = "Hi, this is just a sentence"
# Originally, we need to do it this way
chosen_index = random.randrange(0, len(sentence)) # get a random index first
print(chosen_index)
print(sentence[chosen_index]) # then get the element

# Python provides this method to do it easier
print(random.choice(sentence))
20
e
c
import random

fruits = ["apple", "banana", "Cherry"]
result1 = random.choices(fruits, weights=[1, 1, 2], k=10)
print(result1)

result2 = random.choices(fruits, cum_weights=[1, 2, 4], k=10)
print(result2)
['banana', 'Cherry', 'Cherry', 'apple', 'Cherry', 'Cherry', 'Cherry', 'Cherry', 'apple', 'apple']
['apple', 'Cherry', 'banana', 'banana', 'Cherry', 'banana', 'Cherry', 'banana', 'apple', 'Cherry']
import random

fruits = ["apple", "banana", "Cherry"]
result1 = random.sample(fruits, k=2) #  隨機取樣,三取二
result2 = random.sample(fruits, k=2)
result3 = random.sample(fruits, k=2)
result4 = random.sample(fruits, k=2)
result5 = random.sample(fruits, k=2)

print(result1, result2, result3, result4, result5)
['apple', 'banana'] ['Cherry', 'banana'] ['banana', 'Cherry'] ['Cherry', 'apple'] ['apple', 'Cherry']
import random

fruits = ["apple", "banana", "cherry", "grape", "pear"]
random.shuffle(fruits) #重組 洗牌
print(fruits)
random.shuffle(fruits)
print(fruits)
random.shuffle(fruits)
print(fruits)
['apple', 'grape', 'banana', 'cherry', 'pear']
['banana', 'grape', 'cherry', 'pear', 'apple']
['pear', 'cherry', 'apple', 'banana', 'grape']
# How to shuffle an immutable object, for example - shuffle a tuple
import random

fruits = ("apple", "banana", "cherry", "grape", "pear")
# random.shuffle(fruits) -> TypeError

my_list = random.sample(fruits,k=len(fruits)) # return a new shuffled list
print(my_list)
['grape', 'banana', 'apple', 'cherry', 'pear']

Random Algorithm

  • random.Random is the default PRNG (Pseudo Random Number Generator) in Python

    • uses Mersenne Twister algorithm to generate random numbers
    • most used Mersenne prime → 2**19937 -1 (known as MT19937)
    • However, the Mersenne Twister PRNG is not cryptographically secure
  • random.SystemRandom uses different algorithm behind the scene

    • use /dev/urandom file on POSIX systems (CSPRNG - Cryptographically secure PRNG)
    • use CryptGenRandom() on Windows NT systems (CSPRNG - Cryptographically secure PRNG)
    • gathers entropy from various sources(variations in timing between keystrokes and disk seeks)
  • random number in real life

    • Every encrypted connection on the internet needs some keys
    • Model testing in Machine Learning
    • Game → Enemies appear in different coordinates on the screen
import random

random.seed(10)  # 不管執行幾次,都用同一個 hidden 的 instance
print(random.randint(0, 100)) 

random.seed(10)
print(random.randint(0, 100)) 

random.seed(10)
print(random.randint(0, 100))
73
73
73
import random

random.seed(10)
a = random.Random()
b = random.Random()
a.seed(10)
b.seed(15)
print(a.randint(0, 100))
print(b.randint(0, 100))
73
26
import random

a = random.Random()
b = random.SystemRandom()
print(a.randint(10, 100))
print(b.randint(10, 100))
63
41
2個讚