向量 v = (x, y, z) 的大小 (模長):
|v| = √(x² + y² + z²)
import math
def vector_magnitude(x, y, z):
return math.sqrt(x*x + y*y + z*z)
# 互動式輸入
comps = []
for axis in ['x', 'y', 'z']:
val = float(input(f'Enter {axis} component: '))
comps.append(val)
mag = vector_magnitude(*comps)
print(f'The magnitude of vector is {mag}')
import numpy as np
v = np.array([1.5, -2.0, 3.2])
mag = np.linalg.norm(v) # 或 np.sqrt(np.sum(v**2))
print(mag)
優點:簡潔、高效、支援批次運算 (二維陣列一次算多向量)。
def magnitude(vector):
return math.sqrt(sum(x*x for x in vector))
# 或 NumPy
def magnitude_np(vector):
return np.linalg.norm(vector)