np.round(), np.floor(), np.ceil() in NumPy - Time & Space Complexity
We want to understand how the time it takes to run np.round(), np.floor(), and np.ceil() changes as the input size grows.
How does the number of elements affect the work these functions do?
Analyze the time complexity of the following code snippet.
import numpy as np
arr = np.random.rand(n) * 100
rounded = np.round(arr)
floored = np.floor(arr)
ceiled = np.ceil(arr)
This code creates an array of size n with random numbers, then applies rounding, flooring, and ceiling operations element-wise.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Applying the rounding, floor, or ceiling function to each element in the array.
- How many times: Once for each element, so n times.
As the array size grows, the number of operations grows in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 operations |
| 100 | About 100 operations |
| 1000 | About 1000 operations |
Pattern observation: Doubling the input size roughly doubles the work done.
Time Complexity: O(n)
This means the time to run these functions grows linearly with the number of elements in the array.
[X] Wrong: "These functions run in constant time no matter the array size because they are built-in."
[OK] Correct: Even built-in functions must process each element, so the total time depends on how many elements there are.
Understanding how simple element-wise operations scale helps you explain performance in data processing tasks clearly and confidently.
"What if we applied np.round() only to a fixed number of elements regardless of array size? How would the time complexity change?"