[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: To understand recursion, one must first understand recursion (was Re: apple iie overheat question)
- Subject: Re: To understand recursion, one must first understand recursion (was Re: apple iie overheat question)
- From: Scott Hemphill <hemphill@hemphills.net>
- Date: 07 May 2005 17:12:30 -0400
- Newsgroups: comp.sys.apple2
- References: <3yNee.7639$BE3.859@newsread2.news.pas.earthlink.net> <cvPee.38$r04.117@news.oracle.com> <xTPee.11819$tQ.9886@fed1read06> <m3wtqcgifm.fsf@pearl.local> <J2.j2.6b2LI2FUGqaYyib.NR@aqu.candybar.ne.jp>
- Reply-to: hemphill@alumni.caltech.edu
- Sender: hemphill@pearl.local
- Xref: g2news1.google.com comp.sys.apple2:10818
"Hidehiko Ogata" <hog@aqu.candybar.ne.jp> writes:
> Scott Hemphill wrote:
>
> > You could still use recursion, but tame it a little bit by not recalculating
> > a value that has already been calculated:
> >
> > #define MAXTABLE 2000 // or whatever
> > double F(int n)
> > {
> > static double fibtable[MAXTABLE] = {0, 1};
> > static int maxfib = 1;
> > if (n < 0 || n >= MAXTABLE) return 0; // catch error
> > if (n > maxfib) {
> > fibtable[n] = F(n-1) + F(n-2);
> > maxfib = n;
> > }
> > return fibtable[n];
> > }
>
> Hmm, shouldn't today's compilers be smart enough to detect and
> optimize tail-recursion? As in:
>
> double fib(int n)
> {
> return fib_iter(1, 0, n);
> }
>
> double fib_iter(double old, double older, int count)
> {
> return count ? fib_iter(old + older, old, --count) : older;
> }
>
> (Excuse me for butting in... it's an irresistible subject for
> a scheme fan ;)
I don't mind at all. The topic was already straying from the Apple ][.
GNU cc doesn't do this optimization. I'll leave the topic of whether it
should to others.
I was hoping that somebody would bite on my direct calculation for the
Fibonacci sequence, wondering where my "magic constants" came from, and
why it works. I guess most people either already know, or don't care.
Scott
--
Scott Hemphill hemphill@alumni.caltech.edu
"This isn't flying. This is falling, with style." -- Buzz Lightyear