Skip to content

Commit dfbc043

Browse files
Added Broadcasting and VectoriZation
1 parent c96f922 commit dfbc043

File tree

2 files changed

+196
-0
lines changed

2 files changed

+196
-0
lines changed
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
import numpy as np
2+
3+
'''
4+
🔁 Broadcasting in NumPy
5+
Broadcasting allows NumPy to perform operations between arrays of different shapes during arithmetic operations.
6+
It "stretches" the smaller array across the larger one so they have compatible shapes.
7+
'''
8+
9+
# 🎯 Example 1: Subtracting a scalar from each element of a 1D array
10+
arr = np.array([10, 13, 45, 79, 90])
11+
discount = 10 # 10% discount
12+
# Apply the discount using broadcasting
13+
discounted_arr = arr - (arr * (discount / 100))
14+
print("Discounted Array:", discounted_arr)
15+
16+
# Output: [ 9. 11.7 40.5 71.1 81. ] — each element is reduced by 10%
17+
18+
# 🎯 Example 2: Broadcasting with 2D array and scalar
19+
arr_2d = np.array([[2, 3, 4, 8, 10],
20+
[5, 6, 7, 12, 4]])
21+
22+
# Add 10 to every element
23+
print("2D Array + 10:\n", arr_2d + 10)
24+
25+
# Output:
26+
# [[12 13 14 18 20]
27+
# [15 16 17 22 14]]
28+
29+
# 🎯 Example 3: Broadcasting between two arrays of same shape
30+
# Adding a 1D array to each row of the 2D array
31+
print("2D Array + 1D Array:\n", arr_2d + arr)
32+
33+
# Output:
34+
# [[12 16 49 87 100]
35+
# [15 19 52 91 94]]
36+
37+
# ⚠️ Example 4: Broadcasting error
38+
# Attempting to add an incompatible shape [2,3] to a shape (2,5)
39+
try:
40+
print(arr_2d + [2, 3])
41+
except ValueError as e:
42+
print("Broadcasting Error:", e)
43+
44+
# Output: ValueError due to shape mismatch (2,5) vs (2,)
45+
46+
47+
import numpy as np
48+
49+
'''
50+
⚡ Vectorization in NumPy
51+
Vectorization refers to performing operations on entire arrays without using explicit loops.
52+
This leads to faster and more concise code.
53+
'''
54+
55+
array1 = np.array([1, 2, 3])
56+
array2 = np.array([4, 5, 6])
57+
58+
# ➕ Element-wise addition
59+
print("Addition:", array1 + array2)
60+
# Output: [5 7 9]
61+
62+
# ✖️ Scalar multiplication (broadcasting 35 to each element)
63+
print("Scalar Multiplication (array1 * 35):", array1 * 35)
64+
# Output: [ 35 70 105]
65+
66+
# ➗ Modulus operator on array elements
67+
print("Modulo (array2 % 3):", array2 % 3)
68+
# Output: [1 2 0]
69+
70+
# ➗ Division of each element in arr_2d by 2
71+
arr_2d = np.array([[2, 3, 4, 8, 10],
72+
[5, 6, 7, 12, 4]])
73+
print("2D Array Division by 2:\n", arr_2d / 2)
74+
# Output:
75+
# [[1. 1.5 2. 4. 5. ]
76+
# [2.5 3. 3.5 6. 2. ]]
Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,120 @@
1+
# 📦 NumPy Broadcasting and Vectorization
2+
3+
This guide explains two core concepts in NumPy that enable high-performance array operations without the need for explicit Python loops: **Broadcasting** and **Vectorization**.
4+
5+
---
6+
7+
## 📘 Table of Contents
8+
1. Introduction
9+
2. Broadcasting
10+
3. Vectorization
11+
4. Key Differences
12+
5. Conclusion
13+
14+
---
15+
16+
## 1. Introduction
17+
18+
NumPy is optimized for fast numerical operations. Two of its most powerful features are:
19+
- **Broadcasting**: Automatically expanding dimensions to match arrays during operations.
20+
- **Vectorization**: Applying operations to entire arrays at once without explicit iteration.
21+
22+
These help in writing concise, readable, and efficient code for large-scale data processing.
23+
24+
---
25+
26+
## 2. 📡 Broadcasting
27+
28+
Broadcasting allows NumPy to perform operations on arrays of different shapes, by automatically expanding the smaller array to match the shape of the larger one.
29+
30+
### ✅ Example:
31+
```python
32+
import numpy as np
33+
34+
arr = np.array([10, 13, 45, 79, 90])
35+
discount = 10
36+
37+
# Applying scalar discount to each item in array
38+
# Equivalent to arr - (arr * 0.10)
39+
disc_arr = arr - (arr * (discount / 100))
40+
print(disc_arr)
41+
# Output: [ 9. 11.7 40.5 71.1 81. ]
42+
```
43+
44+
### ✅ Broadcasting between 1D and 2D:
45+
```python
46+
arr_2d = np.array([[2, 3, 4, 8, 10],
47+
[5, 6, 7, 12, 4]])
48+
49+
# Broadcasting scalar 10
50+
print(arr_2d + 10)
51+
# Output:
52+
# [[12 13 14 18 20]
53+
# [15 16 17 22 14]]
54+
55+
# Broadcasting 1D array to 2D
56+
arr = np.array([10, 13, 45, 79, 90])
57+
print(arr_2d + arr)
58+
# Output:
59+
# [[12 16 49 87 100]
60+
# [15 19 52 91 94]]
61+
```
62+
63+
### ❌ When shapes are not compatible:
64+
```python
65+
# This will raise an error because the shape [2, 5] and [2,] can't broadcast
66+
print(arr_2d + [2, 3])
67+
# ValueError
68+
```
69+
70+
---
71+
72+
## 3. ⚡ Vectorization
73+
74+
Vectorization allows you to perform operations on entire arrays without using `for` loops.
75+
76+
### ✅ Example:
77+
```python
78+
array1 = np.array([1, 2, 3])
79+
array2 = np.array([4, 5, 6])
80+
81+
# Element-wise addition
82+
print(array1 + array2) # Output: [5 7 9]
83+
84+
# Scalar multiplication
85+
print(array1 * 35) # Output: [35 70 105]
86+
87+
# Modulo operation
88+
print(array2 % 3) # Output: [1 2 0]
89+
90+
# Vectorized division of 2D array
91+
arr_2d = np.array([[2, 3, 4, 8, 10],
92+
[5, 6, 7, 12, 4]])
93+
print(arr_2d / 2)
94+
# Output:
95+
# [[1. 1.5 2. 4. 5. ]
96+
# [2.5 3. 3.5 6. 2. ]]
97+
```
98+
99+
### ✅ Advantages:
100+
- Much faster than using loops
101+
- Less code = better readability
102+
- Takes advantage of underlying C implementations
103+
104+
---
105+
106+
## 4. 🔍 Key Differences
107+
| Feature | Broadcasting | Vectorization |
108+
|----------------|----------------------------------|----------------------------------------|
109+
| Definition | Auto-expanding shapes to match | Applying operations over entire arrays |
110+
| Requirement | Operands of different shapes | Arrays must support element-wise ops |
111+
| Use Case | Mixing scalars with arrays, etc. | Mathematical operations on arrays |
112+
113+
---
114+
115+
## 5. ✅ Conclusion
116+
117+
With **broadcasting**, you can mix and match scalars and arrays. With **vectorization**, you can avoid slow `for` loops entirely. Combined, they make NumPy extremely powerful for numerical computing.
118+
119+
Explore more in the [NumPy documentation](https://numpy.org/doc/stable/).
120+

0 commit comments

Comments
 (0)