-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtutorial_01_big_o_solution.jl
116 lines (96 loc) · 2.5 KB
/
tutorial_01_big_o_solution.jl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
using PyPlot
function fibonacci_sequence()
n = 30
# Evaluate
f = ones(n)
for i = 3:n
f[i] = f[i-1] + f[i-2]
end
# Plot
clf()
semilogy(1:n, f, "-o", label=L"f(n)")
xlabel(L"n")
ylabel(L"f(n)")
legend()
display(gcf())
# Conclusion: `f(n)` looks like a straight line on a `semilogy` plot;
# hence `f(n)` scales exponentially.
end
function triangular_loop()
n = round.(Int, 10.0.^LinRange(0,4,20))
# Evaluate
f = [sum(sum(1 for j = 1:i) for i = 1:n) for n in n]
# Plot
clf()
loglog(n, f, "-o", label=L"f(n)")
loglog(n, n.^2, "k--", label=L"O(n^2)")
xlabel(L"n")
ylabel(L"f(n)")
legend()
display(gcf())
# Conclusion: `f(n)` looks like a straight line on a `loglog` plot with
# slope parallel to `n^2`. hence `f(n)` scales algebraically with order 2.
end
function geometric_series()
n = 1:20
# Evaluate
f = [sum(2.0.^(1:n)) for n in n]
# Plot
clf()
semilogy(n, f, "-o", label=L"f(n)")
xlabel(L"n")
ylabel(L"f(n)")
legend()
display(gcf())
# Conclusion: `f(n)` looks like a straight line on a `semilogy` plot;
# hence `f(n)` scales exponentially.
end
function recursive()
n = 2 .^ (1:20)
# Define function
f = n -> (if n == 1; return 1; else return 2*f(n÷2)+1; end)
# Plot
clf()
loglog(n, f.(n), "-o", label=L"f(n)")
loglog(n, n, "k--", label=L"O(n)")
xlabel(L"n")
ylabel(L"f(n)")
legend()
display(gcf())
# Conclusion: `f(n)` looks like a straight line on a `loglog` plot with
# slope parallel to `n`. hence `f(n)` scales algebraically with order 1.
end
function exp_sqrt()
n = 1:100
# Evaluate
f = @. exp(sqrt(n))
# Plot
clf()
subplot(1,2,1)
loglog(n, f, "-o", label=L"f(n)")
xlabel(L"n")
ylabel(L"f(n)")
subplot(1,2,2)
semilogy(n, f, "-o", label=L"f(n)")
xlabel(L"n")
ylabel(L"f(n)")
legend()
display(gcf())
# Conclusion: `f(n)` is curved upwards in the `loglog` plot but curved
# downwards in the `semilogy` plot; hence `f(n)` scales super-algebraically
# but sub-exponentially.
end
function recursive_2()
n = 2 .^ (1:20)
# Define function
f = n -> (if n == 1; return 1; else return f(n÷2)+1; end)
# Plot
clf()
semilogx(n, f.(n), "-o", label=L"f(n)")
xlabel(L"n")
ylabel(L"f(n)")
legend()
display(gcf())
# Conclusion: `f(n)` looks like a straight line on a `semilogx` plot;
# hence it scales logarithmically.
end