Day 12: NumPy for Numerical Computation

Topics to Cover:

  • Introduction to NumPy
  • Arrays and Basic Operations

Introduction to NumPy

NumPy is a powerful numerical computing library in Python. It provides support for arrays, matrices, and many mathematical functions.

Installing NumPy:
If you don’t have NumPy installed, you can install it using pip:

pip install numpy

NumPy Arrays

NumPy arrays are the main way to store data in NumPy. They are similar to Python lists but offer more functionality and are more efficient for numerical computations.

Creating a NumPy Array:

import numpy as np

# Creating a 1D array
array_1d = np.array([1, 2, 3, 4, 5])

# Creating a 2D array
array_2d = np.array([[1, 2, 3], [4, 5, 6]])

print(array_1d)
print(array_2d)

Basic Operations with NumPy Arrays

NumPy allows you to perform element-wise operations on arrays.

Basic Arithmetic Operations:

# Creating two arrays
a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Element-wise addition
print(a + b)  # Output: [5 7 9]

# Element-wise subtraction
print(a - b)  # Output: [-3 -3 -3]

# Element-wise multiplication
print(a * b)  # Output: [4 10 18]

# Element-wise division
print(a / b)  # Output: [0.25 0.4  0.5]

Dot Product of Two Vectors

The dot product is a scalar value that is the result of an element-wise multiplication of two vectors, followed by the summation of all the products.

Calculating the Dot Product:

# Creating two vectors
v1 = np.array([1, 2, 3])
v2 = np.array([4, 5, 6])

# Calculating the dot product
dot_product = np.dot(v1, v2)

print(dot_product)  # Output: 32

Potential Problems to Solve

Problem 1: Create a NumPy Array and Perform Basic Arithmetic Operations

Task: Create a NumPy array and perform basic arithmetic operations on it.

Solution:

import numpy as np

# Creating an array
array = np.array([10, 20, 30, 40, 50])

# Performing arithmetic operations
array_add = array + 5
array_sub = array - 5
array_mul = array * 2
array_div = array / 2

print("Original Array:", array)
print("After Addition:", array_add)
print("After Subtraction:", array_sub)
print("After Multiplication:", array_mul)
print("After Division:", array_div)

Problem 2: Calculate the Dot Product of Two Vectors

Task: Write a program to calculate the dot product of two vectors.

Solution:

import numpy as np

# Creating two vectors
vector1 = np.array([1, 3, -5])
vector2 = np.array([4, -2, -1])

# Calculating the dot product
dot_product = np.dot(vector1, vector2)

print("Dot Product:", dot_product)  # Output: 3

Conclusion

NumPy is a fundamental library for numerical computations in Python. By mastering NumPy arrays and operations, you can perform efficient numerical computations with ease.


Stay tuned for Day 13 of the python4ai 30-day series, where we will continue exploring advanced Python topics to enhance our programming skills!

Team
Team

This account on Doubtly.in is managed by the core team of Doubtly.

Articles: 418