0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use floor and ceil Functions in NumPy

Use numpy.floor() to round numbers down to the nearest integer and numpy.ceil() to round numbers up to the nearest integer. Both functions work element-wise on arrays and return new arrays with the rounded values.
๐Ÿ“

Syntax

numpy.floor(x): Returns the largest integer less than or equal to each element in x.

numpy.ceil(x): Returns the smallest integer greater than or equal to each element in x.

Both accept a number or an array as input and return an array of floats with the rounded values.

python
import numpy as np

# Syntax examples
floored = np.floor([1.7, -1.2, 3.5])
ceiled = np.ceil([1.7, -1.2, 3.5])
๐Ÿ’ป

Example

This example shows how numpy.floor() rounds numbers down and numpy.ceil() rounds numbers up element-wise in an array.

python
import numpy as np

arr = np.array([1.7, -1.2, 3.5, -3.7, 0])
floored = np.floor(arr)
ceiled = np.ceil(arr)

print('Original:', arr)
print('Floor:', floored)
print('Ceil:', ceiled)
Output
Original: [ 1.7 -1.2 3.5 -3.7 0. ] Floor: [ 1. -2. 3. -4. 0.] Ceil: [ 2. -1. 4. -3. 0.]
โš ๏ธ

Common Pitfalls

  • Both floor and ceil return floats, not integers, so the result type is float64 even if input is integers.
  • Negative numbers behave differently: floor(-1.2) is -2.0 (rounds down), while ceil(-1.2) is -1.0 (rounds up).
  • Do not confuse floor with truncation; truncation just removes decimals without rounding down.
python
import numpy as np

arr = np.array([-1.7, 1.7])

# Wrong: using astype(int) truncates instead of flooring
truncated = arr.astype(int)

# Correct: use floor for rounding down
floored = np.floor(arr)

print('Truncated:', truncated)
print('Floored:', floored)
Output
Truncated: [-1 1] Floored: [-2. 1.]
๐Ÿ“Š

Quick Reference

FunctionDescriptionExample InputExample Output
numpy.floor(x)Rounds down to nearest integer[1.7, -1.2][1.0, -2.0]
numpy.ceil(x)Rounds up to nearest integer[1.7, -1.2][2.0, -1.0]
โœ…

Key Takeaways

Use numpy.floor() to round numbers down to the nearest integer.
Use numpy.ceil() to round numbers up to the nearest integer.
Both functions work element-wise on arrays and return float arrays.
Negative numbers round differently: floor goes down, ceil goes up.
Avoid confusing floor with truncation; truncation just cuts decimals.