- v1: O(n)< /p>
- v2: O(n/2)
- v3: O(sqrt(n))
Код: Выделить всё
# Sample data
test_list = np.array([...]) # Input sizes
times_v1 = np.array([...]) # Execution times for v1
times_v2 = np.array([...]) # Execution times for v2
times_v3 = np.array([...]) # Execution times for v3
# For v1: O(n)
C_v1 = times_v1[0] / test_list[0]
theoretical_v1 = [(x)/C_v1 for x in test_list]
# For v2: O(n/2)
C_v2 = times_v2[0] / (test_list[0] / 2)
theoretical_v2 = [(x/2)/C_v1 for x in test_list]
# For v3: O(√n)
C_v3 = times_v3[0] / test_list[0]
# This should correctly represent O(√n)
theoretical_v3 = [np.sqrt(x)/C_v1 for x in test_list]
# Plotting
plt.figure(figsize=(14, 8))
# Actual execution times
plt.plot(test_list, times_v1, 'o-', label="v1: O(n)", color="blue")
# Theoretical complexities
plt.plot(test_list, theoretical_v1, '--',
label="Theoretical O(n)", color="blue")
plt.xlabel("Input Size (n)")
plt.ylabel("Time (ms)")
plt.title("Prime Number Check: Execution Time vs Theoretical Complexity")
plt.legend()
plt.show()
Код: Выделить всё
plt.plot(test_list, times_v2, 'o-', label="v2: O(n/2)", color="green")
plt.plot(test_list, theoretical_v2, '--',
label="Theoretical O(n/2)", color="green")
plt.xlabel("Input Size (n)")
plt.ylabel("Time (ms)")
plt.title("Prime Number Check: Execution Time vs Theoretical Complexity")
plt.legend()
plt.show()
Код: Выделить всё
plt.plot(test_list, times_v3, 'o-', label="v3: O(√n)", color="red")
plt.plot(test_list, theoretical_v3, '--',
label="Theoretical O(√n)", color="red")
plt.xlabel("Input Size (n)")
plt.ylabel("Time (ms)")
plt.title("Prime Number Check: Execution Time vs Theoretical Complexity")
plt.legend()
plt.show()
Есть ли способ последовательно масштабировать теоретические кривые динамически во всем диапазоне ввода, не прибегая к жестко запрограммированным константам? Или существует стандартная практика решения таких проблем масштабирования?
Подробнее здесь: https://stackoverflow.com/questions/791 ... matplotlib