萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python 計算三維向量大小:數學公式與 NumPy 實作

數學公式

向量 v = (x, y, z) 的大小 (模長):

|v| = √(x² + y² + z²)

純 Python 實作


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}')

NumPy 向量化實作 (推薦科學計算)


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)

應用場景

  • 物理模擬:速度、加速度、力向量大小
  • 電腦圖形:光線追蹤、法向量正規化
  • 機器學習:特徵向量距離、正規化
copyright © 萬盛學電腦網 all rights reserved