8

I was programming Fibonacci numbers using tail recursion and it seems like the idea behind it is same as Dynamic programming. So are they same? or rather there is some amount of similarity between them? If not when are the cases when they get different?

gizgok
  • 7,303
  • 21
  • 79
  • 124

3 Answers3

4

The terms themselves, although related, are not equivalent by any means:

  • Dynamic programming is a problem solving methodology which can be implemented with or without using tail recursion. More generically, it requires "memoization".

  • Tail recursion is a common way to implement a dynamic programming algorithm, because it specifically applies memoization logic to a specific field.

jayunit100
  • 17,388
  • 22
  • 92
  • 167
  • How does tail recursion "specifically appl[y] memoization logic to a specific field"? – Matt Fenwick Oct 01 '12 at 13:12
  • well, when you tail recur, you just send in the last calculated value, rather than filling up the stack with a bunch of function calls that haven't yet been executed. This is the same as memoization in a looping construct that rebinds a variable over and over again. – jayunit100 Oct 01 '12 at 20:02
1

I can see why you're asking this question. The idea behind dynamic programming is to break a problem into smaller problems, and this is the exact same idea behind many recursive (tail or not) functions.

This is really an apples to oranges kind of comparison that has plenty of good answers, but here's one thing that makes you realize why it's so hard to compare the two ideas: in some languages, including Java, you technically can't use tail recursion. As you might know, a tail recursive function doesn't store a stack of results from its calls and use them later. In Java, however, a stack trace is maintained for every method call. This uses stack space, and can stack overflow if it runs too many times. Therefore, any Java methods that might look tail recursive actually aren't.

Chris
  • 440
  • 3
  • 8
0

Dynamic programming is typically a more effective method to do the same task as is done by tail recursion. The main difference is that dynamic programming stores results already calculated so that if the same operation comes up, instead of the code's being run again, the value is simply looked up. This takes up more space/memory, but results in a faster algorithm.

In the case of fibonacci, the dynamic programming solution would be to constantly add the last two elements in an array to get the next one. The tail recursion solution would calculate each value of fibonacci from scratch.

Cezary Wojcik
  • 21,745
  • 6
  • 36
  • 36
  • This answer seems to imply that dynamic programming can be used to replace tail recursion; this really isn't true, as tail recursion (and tail recursion optimization) are very important implementation techniques which are much more broadly applicable in functional programming. – Matt Fenwick Oct 01 '12 at 14:23