Vector Addition and Subtraction in Python

Welcome to this tutorial. Here we shall learn how to perform Vector addition and subtraction in Python.

A vector in programming terms refers to a one-dimensional array. An array is one of the data structures that stores similar elements i.e elements having the same data type.
The general features of the array include

  • An array can contain many values based on the same name.
  • Accessing the elements is based on the index number. If the array size is ā€œnā€ the last index value is [n-1] and the starting index always [0].
  • We can also slice the elements in the array [start: end] based on the start and end position.

Addition and Subtraction of Vectors in Python

Now let’s learn how to perform the basic mathematical operations such as addition and subtraction on arrays in Python.

To perform this task we need to know about the Numpy module in Python. The Numpy is the Numerical Python that has several inbuilt methods that shall make our task easier.

The easiest and simplest way to create an array in Python is by adding comma-separated literals in matching square brackets. For example
A = [1, 2,3]
B = [4,5,6]
We can even create multidimensional arrays, for example, a two-dimensional array as shown below :
A = ([1,2,3], [4,5,6])
B = ([2,-4,7] , [5,-20,3])

To use this amazing module, we need to import it.
Let’s look into the code to utilize this module for vector addition and subtraction in Python.

import numpy as NP
A = [4, 8, 7]
B = [5, -4, 8]
print("The input arrays are :\n","A:",A ,"\n","B:",B)
Res= NP.add(A,B)
print("After addition the resulting array is :",Res)

So, in the above code, variables A and B are used to store the array elements. To perform the addition we need to call the add() method of NumPy module as NP.add(). Here we have aliased the NumPy as NP which is not necessary we can directly write as NumPy.add().

To perform subtraction on the same array elements, just we need to write another line of code invoking the subtract method i.e NP.subtract() and print the result obtained after the subtraction.

Code is as written below :

import numpy as NP
A = [4, 8, 7] 
B = [5, -4, 8] 
print("The input arrays are :\n","A:",A ,"\n","B:",B)
Res1= NP.add(A,B)
Res2= NP.subtract(A,B) 
print("Result of Addition is :",Res1,"\n","Result of Subtraction is:",Res2)


The input arrays are :
A = [4, 8, 7]
B = [5,-4,8]
Result of Addition is : [9 4 15]
Result of Subtraction is : [-1 12 -1]

Also read:

Leave a Reply