模組:PythonScript/Examples/MyPyMath.py
外觀
import math
# 1. 費氏數列計算 (O(log n) 快速倍增法)
# 效能極高且遞迴深度極淺 (計算 n=100 僅需約 7 層遞迴),完美避開 Stack Overflow 限制
def _fib_fast_doubling(n):
if n == 0:
return (0, 1)
else:
a, b = _fib_fast_doubling(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
def calc_fibonacci(n):
"""計算第 n 個費氏數"""
if not isinstance(n, int):
raise TypeError("n must be an integer")
if n < 0:
raise ValueError("n must be non-negative")
return _fib_fast_doubling(n)[0]
# 2. 具備實際運算功能的 2D 向量類別
class MyVector:
def __init__(self, x, y):
self.x = x
self.y = y
def norm(self):
"""計算向量長度 (L2 Norm / 歐幾里得距離)"""
return math.hypot(self.x, self.y)
def __add__(self, other):
"""支援向量相加 (v1 + v2)"""
if isinstance(other, MyVector):
return MyVector(self.x + other.x, self.y + other.y)
return NotImplemented
def __mul__(self, scalar):
"""支援向量與純量相乘 (v * 3)"""
if isinstance(scalar, (int, float)):
return MyVector(self.x * scalar, self.y * scalar)
return NotImplemented
def __rmul__(self, scalar):
"""支援純量與向量相乘 (3 * v)"""
return self.__mul__(scalar)
def __repr__(self):
"""優化 print 輸出格式"""
return f"MyVector(x={self.x}, y={self.y})"
if __name__ == "__main__":
# 可直接像呼叫原生 Lua 函式一樣呼叫 Python 函式或實例化 Python 類別!
print(f"fib(100)={calc_fibonacci(100)}")
obj = MyVector(3, 4)
print(obj.norm())