w3resource

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


10. Floor, Ceiling, and Truncation

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.].


For more Practice: Solve these Related Problems:

  • Implement a function that computes the floor, ceil, and truncation of each element in an array using np.floor, np.ceil, and np.trunc.
  • Test these operations on an array with a mix of positive and negative floats and verify the outputs.
  • Return a tuple of arrays (floor, ceil, trunc) and compare the results with expected mathematical behavior.
  • Apply these operations along a specified axis of a multi-dimensional array and check for consistency.

Go to:


PREV : Nearest Integer Rounding
NEXT : Matrix Product of Real Numbers

Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.