|
| 1 | +import numpy as np |
| 2 | +import matplotlib.pyplot as plt |
| 3 | + |
| 4 | +# Data range |
| 5 | +n = np.arange(2, 101) |
| 6 | + |
| 7 | +# Big O example: f(n) = n log n, upper bound g(n) = n^2 (showing f(n) = O(n^2)) |
| 8 | +f_big_o = n * np.log2(n) |
| 9 | +upper_bound_big_o = n ** 2 |
| 10 | + |
| 11 | +plt.figure() |
| 12 | +plt.scatter(n, f_big_o, label=r"$f(n) = n \log_2 n$ (data points)", s=10) |
| 13 | +plt.plot(n, upper_bound_big_o, label=r"Upper bound $g(n) = n^2$", linewidth=1.5) |
| 14 | +plt.title("Big O Notation: $f(n) = O(n^2)$") |
| 15 | +plt.xlabel("n") |
| 16 | +plt.ylabel("Time / Growth") |
| 17 | +plt.legend() |
| 18 | +plt.grid(True) |
| 19 | + |
| 20 | +# Big Omega example: f(n) = n log n, lower bound h(n) = n (showing f(n) = Ω(n)) |
| 21 | +f_big_omega = n * np.log2(n) |
| 22 | +lower_bound_big_omega = n |
| 23 | + |
| 24 | +plt.figure() |
| 25 | +plt.scatter(n, f_big_omega, label=r"$f(n) = n \log_2 n$ (data points)", s=10) |
| 26 | +plt.plot(n, lower_bound_big_omega, label=r"Lower bound $h(n) = n$", linewidth=1.5) |
| 27 | +plt.title("Big Omega Notation: $f(n) = \Omega(n)$") |
| 28 | +plt.xlabel("n") |
| 29 | +plt.ylabel("Time / Growth") |
| 30 | +plt.legend() |
| 31 | +plt.grid(True) |
| 32 | + |
| 33 | +# Theta example: noisy f(n) around n log n, bounds 0.8*n log n and 1.2*n log n |
| 34 | +base_theta = n * np.log2(n) |
| 35 | +np.random.seed(42) |
| 36 | +f_theta = base_theta * (1 + np.random.uniform(-0.15, 0.15, size=n.shape)) |
| 37 | +lower_theta = 0.8 * base_theta |
| 38 | +upper_theta = 1.2 * base_theta |
| 39 | + |
| 40 | +plt.figure() |
| 41 | +plt.scatter(n, f_theta, label=r"Noisy $f(n) \approx n \log_2 n$", s=10) |
| 42 | +plt.plot(n, lower_theta, label=r"Lower tight bound $0.8 \cdot n \log_2 n$", linewidth=1.5) |
| 43 | +plt.plot(n, upper_theta, label=r"Upper tight bound $1.2 \cdot n \log_2 n$", linewidth=1.5) |
| 44 | +plt.title("Theta Notation: $f(n) = \Theta(n \log n)$") |
| 45 | +plt.xlabel("n") |
| 46 | +plt.ylabel("Time / Growth") |
| 47 | +plt.legend() |
| 48 | +plt.grid(True) |
| 49 | + |
| 50 | +plt.show() |
0 commit comments