-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoptimizing-fibonacci-computation.html
201 lines (184 loc) · 13.2 KB
/
optimizing-fibonacci-computation.html
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
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="generator" content="Pelican" />
<title>Optimizing Fibonacci Computation</title>
<link rel="stylesheet" href="https://yashaslokesh.github.io/theme/css/main.css" />
<link href="https://yashaslokesh.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate" title="Yashas's Blog Atom Feed" />
<meta name="description" content="We go over my linear-algebra inspired algorithms to compute Fibonacci numbers" />
</head>
<body id="index" class="home">
<header id="banner" class="body">
<h1><a href="https://yashaslokesh.github.io/">Yashas's Blog</a></h1>
<nav><ul>
<li><a href="https://yashaslokesh.github.io/pages/about-me.html">About</a></li>
<li><a href="https://yashaslokesh.github.io/category/misc.html">misc</a></li>
<li class="active"><a href="https://yashaslokesh.github.io/category/python.html">Python</a></li>
</ul></nav>
</header><!-- /#banner -->
<section id="content" class="body">
<article>
<header>
<h1 class="entry-title">
<a href="https://yashaslokesh.github.io/optimizing-fibonacci-computation.html" rel="bookmark"
title="Permalink to Optimizing Fibonacci Computation">Optimizing Fibonacci Computation</a></h1>
</header>
<div class="entry-content">
<footer class="post-info">
<abbr class="published" title="2018-12-28T08:46:00-05:00">
Published: Fri 28 December 2018
</abbr>
<br />
<abbr class="modified" title="2018-12-28T08:46:00-05:00">
Updated: Fri 28 December 2018
</abbr>
<address class="vcard author">
By <a class="url fn" href="https://yashaslokesh.github.io/author/yashas-lokesh.html">Yashas Lokesh</a>
</address>
<p>In <a href="https://yashaslokesh.github.io/category/python.html">Python</a>.</p>
<p>tags: <a href="https://yashaslokesh.github.io/tag/python.html">python</a> <a href="https://yashaslokesh.github.io/tag/algorithms.html">algorithms</a> </p>
</footer><!-- /.post-info --> <p>I posted about this on <a href="https://twitter.com/yashaslokesh_/status/1078510658633846785">Twitter</a> yesterday.</p>
<p>I've been attempting to study the topic of algorithms this break because one of my classes next semester will cover exactly that. I came upon an MIT series of lectures for a class named "Introduction to Algorithms", and I reached <a href="https://youtu.be/OQ5jsbhAv_M">this video</a> yesterday on dynamic programming.</p>
<p>The professor says that there is a O(log <em>n</em>) algorithm for computing fibonacci numbers, and I'm instantly intrigued. I assumed that O(<em>n</em>) was the best that could be accomplished because all of the fibonacci functions we used in our classes were written that way.</p>
<p>I went to <a href="https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form">this Wikipedia article</a> and started reading.
In particular, they list this formula:
</p>
<div class="math">$$
** \begin{pmatrix}
1 & 1 \\
1 & 0 \\
\end{pmatrix}**^{n}
=
\begin{pmatrix}
F_{n+1} & F_{n} \\
F_{n} & F_{n-1} \\
\end{pmatrix}
$$</div>
<p>I realized that I could use numpy to represent the first matrix, and I could use a loop up to a number <em>n</em>, continuously multiplying a resultant matrix with the first matrix above. This is one way to get a O(<em>n</em>) algorithm.</p>
<p>Here's the code for a linear fibonacci function. I know numpy has a matrix_power() method, but that method is optimized for calculation and doesn't help to demonstrate the linear runtime of the code below.
<script src="https://gist.github.com/yashaslokesh/604c6343478eea17c5171b386d186008.js"></script></p>
<p>Now to make the O(log <em>n</em>) algorithm. These types of algorithms are usually created by splitting the input in half many times. I chose an arbitrary <em>n</em>=10. The exponent rule of </p>
<div class="math">$$ a^n * a^m = a^{n + m} (1) $$</div>
<p>
still applies for matrices. Along this line of logic, if we want to compute the fibonacci matrix for <em>n</em>=10, we can multiply two fibonacci matrices of power <em>n</em>=5. That is, </p>
<div class="math">$$ A^5 * A^5 = A^{10} $$</div>
<p>and the second and third entries of the resultant matrix will be our desired fibonacci numbers for <em>n</em>=10. Now we have to figure out a way to find the fibonacci matrix for <em>n</em>=5. Five isn't divisible by two, so we'll have to use a slightly different method. We know</p>
<div class="math">$$ A^2 * A^2 = A^{4} $$</div>
<p>If we multiply the resultant matrix by our base matrix, then</p>
<div class="math">$$ A^4 * A^1 = A^5 $$</div>
<p>We get the desired matrix! So we now have another rule: if the desired matrix has an odd power, we have to multiply two matrices with floor(n / 2) and then multiply once more by the base matrix.</p>
<p>Now we have to figure out a way to start from the base matrix and go up to our desired matrix. Recursion seemed like the best way forward, but I think writing functions iteratively is easier to read, so I'll do it iteratively.</p>
<script src="https://gist.github.com/yashaslokesh/9eba45c889d61391912fcbd435c805b0.js"></script>
<p>In this script, we put 10 into a list. The base case will be where <em>n</em>=1, so we loop and add floor(n / 2) to the list as long as we haven't added one to the end of the list. Here are some examples of what the stack would look like when we finish:</p>
<script src="https://gist.github.com/yashaslokesh/64b97014d59161ce71ecbfb6506852dd.js"></script>
<p>Now we create a matrix <em>result</em>. We know all the possible stacks will have a 1 in its last element, so we can just remove it from the stack without losing any information. Now we can process the numbers in the stack. While the stack is not empty, we multiply <em>result</em> by itself. If the number we popped from the stack is odd, then we multiply <em>result</em> by the base matrix. </p>
<p>Here's the code for this part:</p>
<script src="https://gist.github.com/yashaslokesh/7d32c618c0956e42264334d8ae3231e0.js"></script>
<p>I wanted to test to see if I implemented these algorithms correctly, so I created another module to time these functions. We can use the <strong>timeit</strong> module to time small code snippets. By default, <strong>timeit</strong> will run the code snippet one million times.</p>
<p>Here's the code for the timing part:</p>
<script src="https://gist.github.com/yashaslokesh/d079ed48dce402a43c7f75c289d93678.js"></script>
<p>The code snippet inside <strong>timeit.timeit()</strong> has to be self-contained. It cannot use any external variables. We can, however, pass in a string containing commands that will setup the environment for the code snippet to work. We can use the <strong>make_setup_string()</strong> function for this purpose.</p>
<p>My final results, as I also posted on Twitter, are shown here:</p>
<p><img alt="Image of the timing results, you can look on Twitter if you can't view it here using the link above." src="https://yashaslokesh.github.io/images/lower-res-timings.png"></p>
<p>The timing for the linear_fibonacci() function increases by about 28 seconds every increase of 15 to the input, so we accomplished a linear, or O(<em>n</em>) algorithm.</p>
<p>The timing for the log_fibonacci() function does not follow this same trend. For <em>n</em>=60 and <em>n</em>=90, the timings are lower than the next lower value of <em>n</em>. Even with the input size increasing linearly, there is not a large change in the timing, so we implemented a correct O(log <em>n</em>) algorithm for finding fibonacci numbers.</p>
<p>Thanks for reading! Follow me on Twitter or look at some of my other work on GitHub by clicking on the social links below.</p>
<script type="text/javascript">if (!document.getElementById('mathjaxscript_pelican_#%@#$@#')) {
var align = "center",
indent = "0em",
linebreak = "false";
if (false) {
align = (screen.width < 768) ? "left" : align;
indent = (screen.width < 768) ? "0em" : indent;
linebreak = (screen.width < 768) ? 'true' : linebreak;
}
var mathjaxscript = document.createElement('script');
mathjaxscript.id = 'mathjaxscript_pelican_#%@#$@#';
mathjaxscript.type = 'text/javascript';
mathjaxscript.src = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.3/latest.js?config=TeX-AMS-MML_HTMLorMML';
var configscript = document.createElement('script');
configscript.type = 'text/x-mathjax-config';
configscript[(window.opera ? "innerHTML" : "text")] =
"MathJax.Hub.Config({" +
" config: ['MMLorHTML.js']," +
" TeX: { extensions: ['AMSmath.js','AMSsymbols.js','noErrors.js','noUndefined.js'], equationNumbers: { autoNumber: 'none' } }," +
" jax: ['input/TeX','input/MathML','output/HTML-CSS']," +
" extensions: ['tex2jax.js','mml2jax.js','MathMenu.js','MathZoom.js']," +
" displayAlign: '"+ align +"'," +
" displayIndent: '"+ indent +"'," +
" showMathMenu: true," +
" messageStyle: 'normal'," +
" tex2jax: { " +
" inlineMath: [ ['\\\\(','\\\\)'] ], " +
" displayMath: [ ['$$','$$'] ]," +
" processEscapes: true," +
" preview: 'TeX'," +
" }, " +
" 'HTML-CSS': { " +
" availableFonts: ['STIX', 'TeX']," +
" preferredFont: 'STIX'," +
" styles: { '.MathJax_Display, .MathJax .mo, .MathJax .mi, .MathJax .mn': {color: 'inherit ! important'} }," +
" linebreaks: { automatic: "+ linebreak +", width: '90% container' }," +
" }, " +
"}); " +
"if ('default' !== 'default') {" +
"MathJax.Hub.Register.StartupHook('HTML-CSS Jax Ready',function () {" +
"var VARIANT = MathJax.OutputJax['HTML-CSS'].FONTDATA.VARIANT;" +
"VARIANT['normal'].fonts.unshift('MathJax_default');" +
"VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
"VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
"});" +
"MathJax.Hub.Register.StartupHook('SVG Jax Ready',function () {" +
"var VARIANT = MathJax.OutputJax.SVG.FONTDATA.VARIANT;" +
"VARIANT['normal'].fonts.unshift('MathJax_default');" +
"VARIANT['bold'].fonts.unshift('MathJax_default-bold');" +
"VARIANT['italic'].fonts.unshift('MathJax_default-italic');" +
"VARIANT['-tex-mathit'].fonts.unshift('MathJax_default-italic');" +
"});" +
"}";
(document.body || document.getElementsByTagName('head')[0]).appendChild(configscript);
(document.body || document.getElementsByTagName('head')[0]).appendChild(mathjaxscript);
}
</script>
</div><!-- /.entry-content -->
</article>
</section>
<section id="extras" class="body">
<div class="blogroll">
<h2>links</h2>
<ul>
<li><a href="http://getpelican.com/">Pelican</a></li>
<li><a href="http://python.org/">Python.org</a></li>
<li><a href="http://jinja.pocoo.org/">Jinja2</a></li>
<li><a href="http://tutorial.math.lamar.edu/">Paul's Calc Notes</a></li>
<li><a href="https://www.pygame.org/news">Pygame</a></li>
</ul>
</div><!-- /.blogroll -->
<div class="social">
<h2>social</h2>
<ul>
<li><a href="https://yashaslokesh.github.io/feeds/all.atom.xml" type="application/atom+xml" rel="alternate">atom feed</a></li>
<li><a href="https://twitter.com/yashaslokesh_">My Twitter</a></li>
<li><a href="https://www.linkedin.com/in/yashaslokesh/">My LinkedIn</a></li>
<li><a href="https://github.com/yashaslokesh">My GitHub</a></li>
</ul>
</div><!-- /.social -->
</section><!-- /#extras -->
<footer id="contentinfo" class="body">
<address id="about" class="vcard body">
Proudly powered by <a href="https://getpelican.com/">Pelican</a>, which takes great advantage of <a href="https://www.python.org/">Python</a>.
</address><!-- /#about -->
<p>The theme is by <a href="https://www.smashingmagazine.com/2009/08/designing-a-html-5-layout-from-scratch/">Smashing Magazine</a>, thanks!</p>
</footer><!-- /#contentinfo -->
<script type="text/javascript">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-123139556-3', 'auto');
ga('send', 'pageview');
</script>
</body>
</html>