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:

import numpy as np
x = np.array([-1.6, -1.5, -0.3, 0.1, 1.4, 1.8, 2.0])
print("Original array:")
print(x)
print("Floor values of the above array elements:")
print(np.floor(x))
print("Ceil values of the above array elements:")
print(np.ceil(x))
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.]

Python Code Editor:

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

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 Python skills with w3resource's quiz



Python: Tips of the Day

Getting rid of unwanted characters:

You can get rid of whitespaces or any specific character using strip methods in Python. You can use either plain strip for both sides, lstrip for the left side and rstrip for the right side only.

str="+++Welcome python+++"
str.strip()

print(str)

Output:

+++Welcome python+++