Ufunc Arithmetic
Submitted by moazkhan on Friday, July 10, 2020 - 22:03.
In this tutorial you will learn:
- What are Arithmetic functions?
- How to implement simple arithmetic function?
- Python Syntax
Arithmetic function
Arithmetic operations are the simple operations of addition, subtraction, multiplication and division. The simple arithmetic universal functions in python can take in an array as well as lists and tuples to perform the index wise operations of addition, subtraction, multiplication and division. The simple arithmetic functions can be performed unconditionally and conditionally as well. The ufunc arithmetic functions takes a parameter “where” that ensures that the results are produced conditionally.Implement simple arithmetic function
Inorder to comprehend the implementation of arithmetic functions, lets take an example, here we will be adding up two tuples. Here in the first line of code we are importing the NumPy lib, and declaring each tuple in subsequent lines. Here you can observe that the arithmetic functions can perform operations on data structures other than arrays as well.- #importing the numpy lib
- import numpy as np
- #Declaring the first tuple
- tup1 = (1,3,5,7,9,11)
- #Declaring the second tuple
- tup2 = (2,4,6,8,10,12)
- #adding up two tuples using add() arithmetic ufunc
- res = np.add(tup1,tup2)
- print('Result after adding up two tuples:')
- print(res)
- #importing the numpy lib
- import numpy as np
- #Declaring the first array
- array_1 = np.array([1,3,5,7,9,11])
- #Declaring the second array
- array_2 = np.array([2,4,6,8,10,12])
- #adding up two arrays using add() arithmetic ufunc
- res_arr = np.add(array_1,array_2)
- print('Result after adding up two arrays:')
- print(res_arr)
- #importing the numpy lib
- import numpy as np
- #Declaring the first array
- tup1 = (11,13,15,17,19,21)
- #Declaring the second array
- tup2 = (1,2,3,4,5,6)
- #subtracting two arrays using subtract() arithmetic ufunc
- tup_res = np.subtract(tup1, tup2)
- print('Result after subtracting two tuples:')
- print(tup_res)
- #importing the numpy lib
- import numpy as np
- #Declaring the first tuple
- tup1 = (1,2,3,4,5,6)
- #Declaring the second tuple
- tup2 = (20,30,40,50,60,70)
- #multiplying two arrays using multiply() arithmetic ufunc
- tup_res = np.multiply(tup1, tup2)
- print('Result after multiplying two tuples:')
- print(tup_res)
- #importing the numpy lib
- import numpy as np
- #Declaring the first tuple
- tup1 = (10,20,30,40,50,60)
- #Declaring the second tuple
- tup2 = (1,2,3,4,5,6)
- #divide two arrays using divide() arithmetic ufunc
- tup_res = np.divide(tup1, tup2)
- print('Result after dividing two tuples:')
- print(tup_res)
Add new comment
- 86 views