0
0
NumPydata~5 mins

Trigonometric functions (sin, cos, tan) in NumPy - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Trigonometric functions (sin, cos, tan)
O(n)
Understanding Time Complexity

We want to understand how the time needed to calculate trigonometric functions changes as we increase the amount of data.

Specifically, how does computing sin, cos, or tan for many numbers affect the time it takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.

import numpy as np

angles = np.linspace(0, 2 * np.pi, 1000)
sin_values = np.sin(angles)
cos_values = np.cos(angles)
tan_values = np.tan(angles)

This code creates 1000 angles evenly spaced from 0 to 2π and calculates their sine, cosine, and tangent values.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Computing sin, cos, and tan for each angle in the array.
  • How many times: Once for each of the 1000 angles, so 1000 times per function.
How Execution Grows With Input

As the number of angles increases, the total calculations increase proportionally.

Input Size (n)Approx. Operations
10About 10 sin, 10 cos, and 10 tan calculations
100About 100 sin, 100 cos, and 100 tan calculations
1000About 1000 sin, 1000 cos, and 1000 tan calculations

Pattern observation: The total work grows directly with the number of input angles.

Final Time Complexity

Time Complexity: O(n)

This means the time to compute these functions grows in a straight line as the input size grows.

Common Mistake

[X] Wrong: "Calculating sin, cos, and tan for many numbers takes the same time no matter how many numbers there are."

[OK] Correct: Each number requires its own calculation, so more numbers mean more total work and more time.

Interview Connect

Understanding how time grows with input size helps you explain the efficiency of your code clearly and confidently.

Self-Check

"What if we only calculated sin for half the angles but calculated cos and tan for all? How would the time complexity change?"