Personal blog written from scratch using Node.js, Bootstrap, and MySQL. https://jrtechs.net
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

392 lines
9.7 KiB

  1. If you have ever taken a computer science class you probably
  2. know what the fibonacci sequence is and how to calculate it.
  3. For those who don't know: [Fibonacci](https://en.wikipedia.org/wiki/Fibonacci)
  4. is a sequence of numbers starting with 0,1 whose next number is the sum
  5. of the two previous numbers. After having multiple of my CS classes
  6. gave lectures and multiple homework on the Fibonacci sequence; I decided
  7. that it would be a great idea to write a blog post going over
  8. the 4 main ways of calculating the nth term of the Fibonacci sequence.
  9. In addition to providing python code for calculating the nth perm of the sequence, a proof for their validity
  10. and analysis of their time complexities both mathematically and empirically will
  11. be examined.
  12. # Slow Recursive Definition
  13. By the definition of the Fibonacci sequence, it is the most natural to write it as
  14. a recursive definition.
  15. ```Python
  16. def fib(n):
  17. if n == 0 or n == 1:
  18. return n
  19. return fib(n-1) + fib(n-2)
  20. ```
  21. ##Time Complexity
  22. Observing that each call has two recursive calls we can place an upper bound on this
  23. function as $O(2^n)$. However, if we solve this recurrence we can compute the exact value
  24. and place a tight bound for time complexity.
  25. We can write a recurrence for the number of times fib is called:
  26. $$
  27. F(0) = 0\\
  28. F(1) = 1\\
  29. F(n) = F(n-1) + F(n-2)\\
  30. $$
  31. Next we replace each instance of F(n) with $a^n$ since we want to solve for the roots since that
  32. will allow us to put a tight asymptotic limit on the growth.
  33. $$
  34. a^n = a^{n-1} + a^{n-2}\\
  35. \frac{a^n}{a^{n-2}} = \frac{a^{n-1} + a^{n-2}}{a^{n-2}}\\
  36. a^2 = a + 1\\
  37. a = \frac{1 + sqrt(5)}{2}\\
  38. $$
  39. From this calculation we can conclude that F(n) $\in \Theta 1.681^n$
  40. ## Measured Performance
  41. Here is a graph of the actual performance that I observed from this recursive definition of Fibonacci.
  42. ![Recursive Definition](media/fibonacci/RecursiveDefinition.png)
  43. # Accumulation Solution
  44. The problem with the previous recursive solution is that you had to recalculate certain
  45. terms of fibonacci a ton of times. A summation variable would help us avoid this problem.
  46. You could write this using a simple loop, however, it is still possible to do this with
  47. recursion.
  48. ```Python
  49. def fibHelper(n, a, b):
  50. if n == 0:
  51. return a
  52. elif n == 1:
  53. return b
  54. return fibHelper(n-1, b, a+b)
  55. def fibIterative(n):
  56. return fibHelper(n, 0, 1)
  57. ```
  58. In this code example fibHelper is a method which accumulates the previous two terms.
  59. The fibIterative is a wrapper method which sets the two initial terms equal to 0 and 1
  60. representing the fibonacci sequence.
  61. ## Proof for Fib Helper
  62. **Lemma:** For any n $\epsilon$ N if n $>$ 1 then
  63. $fibHelper(n, a, b) = fibHelper(n - 1, a, b) + fibHelper(n - 2, a, b)$.
  64. **Proof via Induction**
  65. Base Case: n = 2:
  66. $$
  67. LHS = fibHelper(2, a, b)\\
  68. = fibHelper(1, b, a + b) = a + b\\
  69. RHS = fibHelper(2 -1, a, b) + fibHelper(2-2, a, b)\\
  70. = a + b\\
  71. $$
  72. Inductive Step:
  73. Assume proposition is true for all n and show n+1 follows.
  74. $$
  75. RHS=fibHelper(n+1;a,b)\\
  76. = fibHelper(n;b,a+b)\\
  77. =fibHelper(n-1;b,a+b) + fibHelper(n-2;b,a+b)\\
  78. =fibHelper(n;a,b) + fibHelper(n-1;a,b)\\
  79. =LHS\\
  80. $$
  81. $\Box$
  82. ## Proof That fibIterative = Fib
  83. **Lemma:** For any n $\in$ N, $fib(n)$ = $fibIterative(n, 0, 1)$
  84. **Proof via Strong Induction**
  85. Base Case: n = 0:
  86. $$
  87. fibIterative(0, 0, 0) = 0\\
  88. = fib(0)
  89. $$
  90. Base Case: n = 1:
  91. $$
  92. fibIterative(1, 0, 0) = 1\\
  93. = fib(1)
  94. $$
  95. Inductive Step:
  96. Assume proposition is true for all n and show n+1 follows.
  97. $$
  98. fib(n+1) = fib(n) + fib(n-1)\\
  99. = fibHelper(n, 0, 1) + fibHelper(n+1, 0 ,1) \quad\text{I.H}\\
  100. = fibHelper(n+1, 0, 1) \quad\text{from result in previous proof}\\
  101. $$
  102. $\Box$
  103. ## Time Complexity
  104. Suppose that we wish to solve for time complexity in terms of the number of additions needed to be
  105. computed. By observing the algorithm for fibHelper we can see that we perform one addition every time
  106. which we have a recursive call. We can now form a recurrence for time complexity and solve for it.
  107. $$
  108. T(0) = 0\\
  109. T(1) = 0\\
  110. T(n) = 1 + T(n-1)\\
  111. T(n) = n-1\\
  112. $$
  113. From this recurrence we can say that fibHelper $\in \Theta(n)$.
  114. ## Measured Performance
  115. Notice how much faster this solution is compared to the original recursive solution for
  116. Fibonacci.
  117. ![Iterative Performance](media/fibonacci/Iterative.png)
  118. # Matrix Solution
  119. We can actually get better than linear time for performance while calculating
  120. the Fibonacci sequence recursively using this fact:
  121. $$
  122. \begin{bmatrix}
  123. 1 & 1\\
  124. 1 & 0
  125. \end{bmatrix}^n =
  126. \begin{bmatrix}
  127. F_{n+1} & F_n\\
  128. F_n & F{n-1}
  129. \end{bmatrix}^n
  130. $$
  131. Without any other tricks, raising a matrix to a power n times would not get
  132. us better than linear performance. However, if we use the [Exponentiation by Squaring](https://en.wikipedia.org/wiki/Exponentiation_by_squaring)
  133. method, we can expect to see logarithmic time. Since two spots in the matrix are always equal,
  134. I represented the matrix as an array with only three elements.
  135. ```Python
  136. def multiply(a,b):
  137. product = [0,0,0]
  138. product[0] = a[0]*b[0] + a[1]*b[1]
  139. product[1] = a[0]*b[1] + a[1]*b[2]
  140. product[2] = a[1]*b[1] + a[2]*b[2]
  141. return product
  142. def power(l, k):
  143. if k == 1:
  144. return l
  145. temp = power(l, k//2)
  146. if k%2 == 0:
  147. return multiply(temp, temp)
  148. else:
  149. return multiply(l, multiply(temp, temp))
  150. def fibPower(n):
  151. l = [1,1,0]
  152. return power(l, n)[1]
  153. ```
  154. ## Time Complexity
  155. For this algorythem lets solve for the time complexity as the number of additions and multiplications.
  156. Since we are always multiplying two 2x2 matrices, that is constant time.
  157. $$
  158. T_{multiply} = 9
  159. $$
  160. Solving for the time complexity of fib power is slightly more complicated.
  161. $$
  162. T_{power}(1) = 0\\
  163. T_{power}(n) = T(\left\lfloor\dfrac{n}{2}\right\rfloor) + T_{multiply}\\
  164. = T(\left\lfloor\dfrac{n}{2}\right\rfloor) + 9\\
  165. = T(\left\lfloor\dfrac{n}{2*2}\right\rfloor) + 9 + 9\\
  166. = T(\left\lfloor\dfrac{n}{2*2*2}\right\rfloor) + 9+ 9 + 9\\
  167. T_{power}(n) = T(\left\lfloor\dfrac{n}{2^k}\right\rfloor) + 9k\\
  168. $$
  169. let $k=k_0$ such that $\left\lfloor\dfrac{n}{2^{k_0}}\right\rfloor = 1$
  170. $$
  171. \left\lfloor\dfrac{n}{2^{k_0}}\right\rfloor = 1 \rightarrow 1 \leq \frac{n}{2^{k_0}} < 2\\
  172. \rightarrow 2^{k_0} \leq n < 2^{k_0 +1}\\
  173. \rightarrow k_0 \leq lg(n) < k_0+1\\
  174. \rightarrow k_0 = \left\lfloor lg(n)\right\rfloor\\
  175. T_{power}(n) = T(1) + 9*\left\lfloor lg(n)\right\rfloor\\
  176. T_{power}(n) = 9*\left\lfloor\ lg(n)\right\rfloor\\
  177. T_{fibPower}(n) = T_{power}(n)\\
  178. $$
  179. ## Inductive Proof for Matrix Method
  180. **Lemma:** For any n $\epsilon$ N if n $>$ 0 then
  181. $$
  182. \begin{bmatrix}
  183. 1 & 1\\
  184. 1 & 0
  185. \end{bmatrix}^n =
  186. \begin{bmatrix}
  187. F_{n+1} & F_n\\
  188. F_n & F{n-1}
  189. \end{bmatrix}^n
  190. $$
  191. Let
  192. $$
  193. A=
  194. \begin{bmatrix}
  195. 1 & 1\\
  196. 1 & 0
  197. \end{bmatrix}^n
  198. $$
  199. **Base Case:** n = 1
  200. $$
  201. A^1=
  202. \begin{bmatrix}
  203. 1 & 1\\
  204. 1 & 0
  205. \end{bmatrix}^n =
  206. \begin{bmatrix}
  207. F_{2} & F_2\\
  208. F_2 & F_{0}
  209. \end{bmatrix}^n
  210. $$
  211. **Inductive Step:** Assume proposition is true for n, show n+1 follows
  212. $$
  213. A^{n+1}=
  214. \begin{bmatrix}
  215. 1 & 1\\
  216. 1 & 0
  217. \end{bmatrix}
  218. \begin{bmatrix}
  219. F_{n+1} & F_n\\
  220. F_n & F{n-1}
  221. \end{bmatrix}^n\\
  222. = \begin{bmatrix}
  223. F_{n+1} + F_n & F_n + F_{n-1}\\
  224. F_{n+1} & F_{n}
  225. \end{bmatrix}\\
  226. = \begin{bmatrix}
  227. F_{n+2} & F_{n+1}\\
  228. F_{n+1} & F_{n}
  229. \end{bmatrix}\\
  230. $$
  231. $\Box$
  232. ## Measured Performance
  233. ![FibPower Performance](media/fibonacci/FibPower.png)
  234. As expected by our mathmatical calcuations, the algorthem appears to be running in
  235. logarithmic time.
  236. ## Measured Performance With Large Numbers
  237. ![FibPower Performance](media/fibonacci/FibPowerBigPicture.png)
  238. When calculating the fibonacci term for extremely large numbers dispite having a polynomial
  239. time complexity, the space required to compute Fibonacci grows exponentially. Since our
  240. performance is only pseudo-polynomial we see a degrade in our performance when calculating
  241. large terms of the fibonacci sequence.
  242. The one amazing thing to point out here is that despite calculating the 10,000 term of Fibonacci,
  243. this algorithm is nearly 400 times faster than the recursive algorithm when it was calculating
  244. the 30th term of Fibonacci.
  245. # Closed Form Definition
  246. It is actually possible to calculate Fibonacci in constant time using Binet's Formula.
  247. $$
  248. F_n = \frac{(\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n}{\sqrt{5}}
  249. $$
  250. ```Python
  251. def fibClosedFormula(n):
  252. p = ((1+ math.sqrt(5))/2)**n
  253. v = ((1-math.sqrt(5))/2)**n
  254. return (p-v)/math.sqrt(5)
  255. ```
  256. ## Derivation of Formula
  257. Similar to when we were calculating for the time complexity, we want to start by finding the
  258. two roots of the equation.
  259. $$
  260. a^n = a^{n-1} + a^{n-2}\\
  261. \frac{a^n}{a^{n-2}} = \frac{a^{n-1} + a^{n-2}}{a^{n-2}}\\
  262. a^2 = a + 1\\
  263. 0 = a^2 - a - 1\\
  264. a = \frac{1 \pm sqrt(5)}{2}\\
  265. $$
  266. Since there are two roots to the equation, the solution of $F_n$ is going to be
  267. a linear combination of the two roots.
  268. $$
  269. F_n = c_1(\frac{1 + \sqrt{5}}{2})^n + c_2(\frac{1 - \sqrt{5}}{2})^n
  270. $$
  271. Fact: $F_1$ = 1
  272. $$
  273. F_1 = 1\\
  274. = c_1(\frac{1 + \sqrt{5}}{2}) + c_2(\frac{1 - \sqrt{5}}{2})\\
  275. = \frac{c_1}{2} + \frac{c_2}{2} + \frac{c_1\sqrt{5}}{2} - \frac{c_2\sqrt{5}}{2}\\
  276. $$
  277. Let $c_1 = \frac{1}{\sqrt{5}}$,
  278. Let $c_2 = \frac{-1}{\sqrt{5}}$
  279. $$
  280. F_n = \frac{1}{\sqrt(5)}((\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n)\\
  281. = \frac{(\frac{1+\sqrt{5}}{2})^n-(\frac{1-\sqrt{5}}{2})^n}{\sqrt{5}}
  282. $$
  283. ## Time Complexity
  284. Since we managed to find the closed form of the fibonacci sequence we can expect to see constant performance.
  285. ## Measured Performance
  286. ![FibPower Performance](media/fibonacci/ConstantTimeComplexity.png)