0
0
NumPydata~5 mins

np.exp() and np.log() in NumPy - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: np.exp() and np.log()
O(n)
Understanding Time Complexity

We want to understand how the time to run np.exp() and np.log() changes as the input size grows.

How does the cost of these functions grow when we apply them to bigger arrays?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import numpy as np

arr = np.random.rand(n)
exp_arr = np.exp(arr)
log_arr = np.log(arr + 1e-10)  # avoid log(0)

This code creates an array of size n, then applies the exponential and logarithm functions element-wise.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Applying np.exp() and np.log() to each element of the array.
  • How many times: Once for each of the n elements in the array.
How Execution Grows With Input

As the array size n grows, the number of operations grows roughly the same way, because each element needs one exponential and one logarithm calculation.

Input Size (n)Approx. Operations
10About 20 operations (10 exp + 10 log)
100About 200 operations
1000About 2000 operations

Pattern observation: The total work grows directly with n, doubling n doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to run these functions grows linearly with the size of the input array.

Common Mistake

[X] Wrong: "np.exp() and np.log() run in constant time no matter the input size."

[OK] Correct: These functions are applied to every element in the array, so the total time grows with the number of elements.

Interview Connect

Knowing how vectorized functions like np.exp() and np.log() scale helps you understand performance when working with large datasets.

Self-Check

"What if we applied np.exp() only to a fixed-size subset of the array instead of the whole array? How would the time complexity change?"