w3resource

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


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: