w3resource

NumPy: Get the floor, ceiling and truncated values of the elements of a numpy array

NumPy Mathematics: Exercise-10 with Solution

Write a NumPy program to get the floor, ceiling and truncated values of the elements of a numpy array.

Sample Solution:

Python Code:

# Importing the NumPy library
import numpy as np

# Creating an array with float values
x = np.array([-1.6, -1.5, -0.3, 0.1, 1.4, 1.8, 2.0])

# Displaying the original array
print("Original array:")
print(x)

# Floor values of the array elements (round down to the nearest integer)
print("Floor values of the above array elements:")
print(np.floor(x))

# Ceil values of the array elements (round up to the nearest integer)
print("Ceil values of the above array elements:")
print(np.ceil(x))

# Truncated values of the array elements (remove decimal part without rounding)
print("Truncated values of the above array elements:")
print(np.trunc(x)) 

Sample Output:

Original array:                                                        
[-1.6 -1.5 -0.3  0.1  1.4  1.8  2. ]                                   
Floor values of the above array elements:                              
[-2. -2. -1.  0.  1.  1.  2.]                                          
Ceil values of the above array elements:                               
[-1. -1. -0.  1.  2.  2.  2.]                                          
Truncated values of the above array elements:                          
[-1. -1. -0.  0.  1.  1.  2.]

Explanation:

x = np.array([-1.6, -1.5, -0.3, 0.1, 1.4, 1.8, 2.0]) - This line creates an array with seven elements.

np.floor(x) – This code returns the largest integer value less than or equal to each element of x. The output is [-2. -2. -1. 0. 1. 1. 2.].

np.ceil(x) – This code returns the smallest integer value greater than or equal to each element of x. The output is [-1. -1. -0. 1. 2. 2. 2.]

np.trunc(x) – This code returns the truncated integer value of each element of x towards zero. The output is [-1. -1. -0. 0. 1. 1. 2.].

Python-Numpy Code Editor:

Previous: Write a NumPy program to round elements of the array to the nearest integer.
Next: Write a NumPy program to multiply a 5x3 matrix by a 3x2 matrix and create a real matrix product.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-math-exercise-10.php