Mathematical constants (pi, e, golden ratio) in SciPy - Time & Space Complexity
We want to understand how fast we can get values of famous math constants using scipy.
How does the time to get these constants change if we ask for many of them?
Analyze the time complexity of the following code snippet.
from scipy import constants
values = []
for _ in range(n):
values.append(constants.pi)
values.append(constants.e)
values.append(constants.golden)
This code collects the constants pi, e, and the golden ratio n times into a list.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Loop running n times, each time fetching 3 constants.
- How many times: The loop runs exactly n times, repeating the constant retrieval 3 times per loop.
Each time we increase n, the number of operations grows directly with n.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 (10 loops x 3 constants) |
| 100 | 300 (100 loops x 3 constants) |
| 1000 | 3000 (1000 loops x 3 constants) |
Pattern observation: The operations increase evenly as n grows; doubling n doubles the work.
Time Complexity: O(n)
This means the time to get all constants grows in a straight line as we ask for more.
[X] Wrong: "Getting constants like pi or e takes a long time or grows with their value."
[OK] Correct: These constants are stored values in scipy, so fetching them is very fast and does not depend on their size or value.
Knowing how simple operations like fetching constants scale helps you understand bigger data tasks better.
"What if instead of fetching constants, we computed them with a complex formula inside the loop? How would the time complexity change?"