numpy 廣播機制
阿新 • • 發佈:2018-11-23
- +. -. *. /都會激發廣播機制
>>> s array([[1], [2], [3]]) >>> ss array([[1, 2], [3, 4], [5, 6]]) >>> s array([[1], [2], [3]]) >>> ss + s array([[2, 3], [5, 6], [8, 9]]) >>> ss - s array([[0, 1], [1, 2], [2, 3]]) >>> ss * s array([[ 1, 2], [ 6, 8], [15, 18]]) >>> ss / s array([[1. , 2. ], [1.5 , 2. ], [1.66666667, 2. ]])
- 標量vs向量/矩陣
- 會自動擴充套件至緯度相等(此處標量->(3, 1))
>>> s array([[1], [2], [3]]) >>> s + 1 array([[2], [3], [4]]) >>> s - 1 array([[0], [1], [2]]) >>> s * 2 array([[2], [4], [6]]) >>> s / 2 array([[0.5], [1. ], [1.5]])
- 向量vs矩陣
- 會自動擴充套件至緯度相等(此處向量->(3, 2))
- 必須要有一個維度是相等的才會發生廣播,否則報錯
>>> s array([[1], [2], [3]]) >>> ss array([[1, 2], [3, 4], [5, 6]]) >>> s array([[1], [2], [3]]) >>> ss + s array([[2, 3], [5, 6], [8, 9]]) >>> ss - s array([[0, 1], [1, 2], [2, 3]]) >>> ss * s array([[ 1, 2], [ 6, 8], [15, 18]]) >>> ss / s array([[1. , 2. ], [1.5 , 2. ], [1.66666667, 2. ]])