w3resource

NumPy: Calculate round, floor, ceiling, truncated and round of the input, element-wise of a given array

NumPy Mathematics: Exercise-26 with Solution

Write a NumPy program to calculate round, floor, ceiling, truncated and round (to the given number of decimals) of the input, element-wise of a given array.

Sample Solution:-

Python Code:

import numpy as np
x = np.array([3.1, 3.5, 4.5, 2.9, -3.1, -3.5, -5.9])
print("Original array: ")
print(x)
r1 = np.around(x)
r2 = np.floor(x)
r3 = np.ceil(x)
r4 = np.trunc(x)
r5 = [round(elem) for elem in x]

print("\naround:   ", r1)
print("floor:    ",r2)
print("ceil:     ",r3)
print("trunc:    ",r4)
print("round:    ",r5)

Sample Output:

Original array: 
[ 3.1  3.5  4.5  2.9 -3.1 -3.5 -5.9]

around:    [ 3.  4.  4.  3. -3. -4. -6.]
floor:     [ 3.  3.  4.  2. -4. -4. -6.]
ceil:      [ 4.  4.  5.  3. -3. -3. -5.]
trunc:     [ 3.  3.  4.  2. -3. -3. -5.]
round:     [3.0, 4.0, 4.0, 3.0, -3.0, -4.0, -6.0]

Python Code Editor:

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

Previous: Write a NumPy program to calculate hyperbolic sine, hyperbolic cosine, and hyperbolic tangent for all elements in a given array.

Next: Write a NumPy program to calculate cumulative sum of the elements along a given axis, sum over rows for each of the 3 columns and sum over columns for each of the 2 rows of a given 3x3 array.

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+++