NumPy Arithmetic Operations, numpy.reciprocal(), numpy.power(), numpy.mod(), Complex array functions in NumPy

NumPy Arithmetic Operations

NumPy is a Python library that provides support for large, multi-dimensional arrays and matrices, along with a large collection of high-level mathematical functions to operate on these arrays. Here's a tutorial on how to perform basic arithmetic operations with NumPy:

Step 1: Importing NumPy

Before you can use NumPy, you need to import it. By convention, it's usually imported under the alias np:

import numpy as np 

Step 2: Creating NumPy Arrays

You can create a NumPy array using the np.array() function:

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

Step 3: Basic Arithmetic Operations

You can perform element-wise arithmetic operations on NumPy arrays just like you would with normal numbers. Here are the basic operations:

Addition

print(a + b) # Output: array([5, 7, 9]) 

Subtraction

print(a - b) # Output: array([-3, -3, -3]) 

Multiplication

print(a * b) # Output: array([ 4, 10, 18]) 

Division

print(a / b) # Output: array([0.25, 0.4 , 0.5 ]) 

Exponentiation

print(a ** b) # Output: array([ 1, 32, 729], dtype=int32) 

Note that these operations are performed element-wise. That means the operation is performed on each pair of elements from the two arrays.

Step 4: Advanced Arithmetic Functions

NumPy also provides several advanced mathematical functions. Here are a few examples:

Square Root

print(np.sqrt(a)) # Output: array([1. , 1.41421356, 1.73205081]) 

Exponential

print(np.exp(a)) # Output: array([ 2.71828183, 7.3890561 , 20.08553692]) 

Sin

print(np.sin(a)) # Output: array([0.84147098, 0.90929743, 0.14112001]) 

Cos

print(np.cos(a)) # Output: array([ 0.54030231, -0.41614684, -0.9899925 ]) 

Log

print(np.log(a)) # Output: array([0. , 0.69314718, 1.09861229]) 

These are just a few examples of what you can do with NumPy. The library provides a wide range of mathematical functions that you can explore in the official NumPy documentation.


More Tags

json5 displayattribute amazon-dynamodb renewal watch adb android-tabs matching spyder junit5

More Programming Guides

Other Guides

More Programming Examples