Universal array functions

Universal functions perform the operations on all the elements in a numpy array. Now, we are going to look at an example to perform multiple universal functions on an array. First, we are going to take the square root of the array. Create a script called sqrt_array.py and write the following content in it:

import numpy as np

array = np.arange(16)
print("The Array is : ",array)
Square_root = np.sqrt(array)
print("Square root of given array is : ", Square_root)

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 sqrt_array.py

The output is as follows:

The Array is : [ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
Square root of given array is : [0. 1. 1.41421356 1.73205081 2. 2.23606798
2.44948974 2.64575131 2.82842712 3. 3.16227766 3.31662479
3.46410162 3.60555128 3.74165739 3.87298335]

In the preceding example, we created one simple array using range as a function of numpy. Then we applied the sqrt() function on the generated array to get the square root of the array. After taking the square root of the array, we are going to apply another universal function on the array, which is the exponential exp() function. Let's look at an example. Create a script called expo_array.py and write the following content in it:

import numpy as np

array = np.arange(16)
print("The Array is : ",array)
exp = np.exp(array)
print("exponential of given array is : ", exp)

Run the script and you will get the following output:

student@ubuntu:~/work$ python3 expo_array.py

The output is as follows:

The Array is :  [ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15]
exponential of given array is : [1.00000000e+00 2.71828183e+00 7.38905610e+00 2.00855369e+01
5.45981500e+01 1.48413159e+02 4.03428793e+02 1.09663316e+03
2.98095799e+03 8.10308393e+03 2.20264658e+04 5.98741417e+04
1.62754791e+05 4.42413392e+05 1.20260428e+06 3.26901737e+06]

In the preceding example, we created one simple array using the range function of numpy. Then we applied the  exp() function on the generated array to get the exponential of the array.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset