Mathematical Operations in NumPy (Fast Calculations Explained)

๐Ÿ“Œ Introduction

One of the biggest advantages of using NumPy is its ability to perform fast mathematical operations on arrays.

Unlike Python lists, NumPy allows vectorized computations, making calculations extremely efficient.


๐Ÿ”ข Basic Arithmetic Operations

NumPy allows element-wise operations.

import numpy as npa = np.array([1, 2, 3])
b = np.array([4, 5, 6])print(a + b)
print(a - b)
print(a * b)
print(a / b)

๐Ÿ‘‰ Output:

[5 7 9]
[-3 -3 -3]
[ 4 10 18]
[0.25 0.4 0.5 ]

โšก Scalar Operations

You can perform operations with a single number.

a = np.array([1, 2, 3])print(a * 2)

๐Ÿ‘‰ Output:

[2 4 6]

๐Ÿ“Š Power & Square Root

import numpy as npa = np.array([1, 4, 9])print(np.sqrt(a))
print(np.power(a, 2))

๐Ÿ‘‰ Output:

[1. 2. 3.]
[ 1 16 81]

๐Ÿ“‰ Logarithmic & Exponential Functions

a = np.array([1, 2, 3])print(np.log(a))
print(np.exp(a))

๐Ÿ”„ Trigonometric Functions

a = np.array([0, np.pi/2, np.pi])print(np.sin(a))
print(np.cos(a))

๐Ÿ“ฆ Aggregation Operations

a = np.array([10, 20, 30])print(np.sum(a))
print(np.min(a))
print(np.max(a))

๐Ÿ‘‰ Output:

60
10
30

โšก Why NumPy is Fast?

NumPy uses:

  • Vectorization (no loops)
  • Optimized C backend
  • Parallel computation

๐Ÿ“Š Real-World Example

prices = np.array([100, 200, 300])discount = prices * 0.9
print(discount)

๐Ÿ‘‰ Output:

[ 90. 180. 270.]

โœ” Useful in:

  • Finance
  • Data analysis
  • Machine learning

๐Ÿ”— Works with Other Libraries

Used in:

  • Pandas
  • TensorFlow
  • Scikit-learn

๐Ÿ“Š Summary Table

OperationFunction
Additiona + b
Multiplicationa * b
Square rootnp.sqrt()
Lognp.log()
Sumnp.sum()

๐Ÿง  Pro Tips

  • Use vectorized operations instead of loops
  • Combine multiple operations for efficiency
  • Use NumPy functions for better performance

๐Ÿ”š Conclusion

Mathematical operations in NumPy are fast, efficient, and essential for modern data processing.


Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *