Perform math functions using NumPy library

Perform Math Functions Using NumPy Library

NumPy is a powerful library in Python that provides support for large multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. It is widely used in scientific computing, data analysis, and machine learning due to its efficiency and ease of use. In this article, we'll explore some basic math functions using NumPy.

Perform math functions using NumPy library

Getting Started with NumPy

Before we dive into examples, make sure you have NumPy installed. You can install it using pip:

pip install numpy

Once installed, you can start using it by importing the library:python

import numpy as np

Here's the entire program to perform math functions using NumPy library. This block of code covers the creation of arrays, basic arithmetic operations, and some advanced mathematical functions using the NumPy library.

import numpy as np
# Creating two arrays
array1 = np.array([1, 2, 3, 4])
array2 = np.array([5, 6, 7, 8])

print("Array 1:", array1)
print("Array 2:", array2)

# Addition
sum_array = np.add(array1, array2)
print("Sum:", sum_array)

# Subtraction
difference_array = np.subtract(array2, array1)
print("Difference:", difference_array)

# Multiplication
product_array = np.multiply(array1, array2)
print("Product:", product_array)

# Division
quotient_array = np.divide(array2, array1)
print("Quotient:", quotient_array)

# Creating an array of angles in radians
angles = np.array([0, np.pi/2, np.pi, 3*np.pi/2])

# Sine
sine_values = np.sin(angles)
print("Sine:", sine_values)

# Cosine
cosine_values = np.cos(angles)
print("Cosine:", cosine_values)

# Tangent
tangent_values = np.tan(angles)
print("Tangent:", tangent_values)

# Exponential
exp_values = np.exp(array1)
print("Exponential:", exp_values)

# Natural Logarithm
log_values = np.log(array2)
print("Logarithm:", log_values)


Expected Output of the program:

Array 1: [1 2 3 4]
Array 2: [5 6 7 8]
Sum: [ 6 8 10 12]
Difference: [4 4 4 4]
Product: [ 5 12 21 32]
Quotient: [5. 3. 2.33333333 2. ]
Sine: [ 0.0000000e+00 1.0000000e+00 1.2246468e-16 -1.0000000e+00]
Cosine: [ 1.0000000e+00 6.1232340e-17 -1.0000000e+00 -1.8369702e-16]
Tangent: [ 0.00000000e+00 1.63312394e+16 -1.22464680e-16 5.44374645e+15]
Exponential: [ 2.71828183 7.3890561 20.08553692 54.59815003]
Logarithm: [1.60943791 1.79175947 1.94591015 2.07944154]

** Process exited - Return Code: 0 **
Press Enter to exit terminal


Conclusion

NumPy provides a wide range of mathematical functions that make it a crucial tool for any data scientist or engineer. Whether you're performing basic arithmetic or advanced mathematical computations, NumPy simplifies the process and allows you to write efficient, readable code.

Experiment with these functions and explore more capabilities of NumPy to enhance your programming skills.

Happy Coding...!

Comments