Trigonometric functions (sin, cos, tan) in NumPy - Time & Space 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?
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 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.
As the number of angles increases, the total calculations increase proportionally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 sin, 10 cos, and 10 tan calculations |
| 100 | About 100 sin, 100 cos, and 100 tan calculations |
| 1000 | About 1000 sin, 1000 cos, and 1000 tan calculations |
Pattern observation: The total work grows directly with the number of input angles.
Time Complexity: O(n)
This means the time to compute these functions grows in a straight line as the input size grows.
[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.
Understanding how time grows with input size helps you explain the efficiency of your code clearly and confidently.
"What if we only calculated sin for half the angles but calculated cos and tan for all? How would the time complexity change?"