Definition of a Fibonacci series :
The first number of the sequence is 0, the second number is 1, and
each subsequent number is equal to the sum of the previous two numbers
of the sequence itself, yielding the sequence 0, 1, 1, 2, 3, 5, 8, etc
Eg:
If N = 8, program needs to print
0 1 1 2 3 5 8 13
I've been told I need to use a recursive subprogram to do this
problem.
I'm new to FORTRAN and could really use help on this ASAP! I need to
do it by the end of the day on Friday, and I have little idea of what
I'm doing. Any help would be greatly appreciated!
Thanks,
BobbyJ124
You do NOT need recursion to solve this problem.
How would you solve the problem with pencil and paper?
Hint, you need 3 "buckets". One for the first number, one for the second
number, one for the new number.
After computing each new number, you need to move the contents of the
"buckets" around.
Since this is obviously a homework assignment, you need to work on this
problem yourself. Post your program and its output and perhaps someone in
this newsgroup will help you.
In the meantime, go to Wikipedia and look up Fortran. Do a Google search on
"Fortran tutorial".
- elliot
thanks elliot,
what do your mean by 'buckets'? i get your idea in terms of how i
would do it by hand, but i'm confused on how to start my code, like
what kind of data types would i use to create those 'buckets'.
unfortunately my professor doesn't speak english very well at all so i
have a hard time learning this stuff from her. our entire class is
doing pretty poorly because of her so there's no one in it that i can
really ask for help. so, any help that people can give me in english
on here is greatly appreciated. my best hope for a good grade is to
stay above the curve lol
thanks elliot,
----> "bucket" is my informal term for *variable*
Fortran has INTEGER (of various kinds), REAL (of various kinds), LOGICAL,
CHARACTER and COMPLEX.
Which of these is appropriate?
-- e
>>
>> > I've been told I need to use a recursive subprogram to do this
>> > problem.
Was this a requirement, or just a friendly suggestion ?
>
>what do your mean by 'buckets'? i get your idea in terms of how i
>would do it by hand, but i'm confused on how to start my code, like
>what kind of data types would i use to create those 'buckets'.
Yes, well. I'm quite sure he didn't mean "buckets" literally.
Google for "fortran data types", then decide which would be the most
appropriate.
What he ment was that you need to get one number and the other one
(first two), then calculate the next in line fib. After that replace
the first with the second, the second with fib ... you get the point.
Just like on paper.
This can be done in 13 lines of very quickly written code. Probably
even less with a little tinkering. So you have plenty of time till
friday. Try solving it by yourself, if it doesn't work, I'll (probably
a few other too) will post the solution.
-- Luka
-- Sorry, I'm totally speechless.
Alright, I'm gonna get to bed now and work on this throughout the
week, but I will be glad to post what I have and hopefully you can
steer me in the right direction. Oh, and recursion was basically just
a suggestion but we can always do something else if we can do it.
Would I want to use the REAL data type for my variable(s)?
thanks alot!
bobby
yeah, good ole' Penn State doesn't really take communication skills
into consideration when hiring professors. Actually my teacher is
just a grad student so its even worse, i've never even seen the actual
professor. "Speechless" is a good word to describe mine, and others
in the class to this teacher...I actually feel bad for her because you
can tell she doesn't want to teach, its just a requirement to get her
degree. One on one, she's a nice person and everything, she just can't
teach a class of 50 people with her style.
Would i want to use REAL?
>
>Alright, I'm gonna get to bed now and work on this throughout the
>week, but I will be glad to post what I have and hopefully you can
>steer me in the right direction. Oh, and recursion was basically just
>a suggestion but we can always do something else if we can do it.
>Would I want to use the REAL data type for my variable(s)?
yes, real for fib, integer for counter
-- Luka
How would one calculate the 1477th Fib (and more) ? Up to, let's say,
10000th ?
Using this principle, no fancy formulas and such ...
-- Luka
You could do that. Or you could use INTEGER. In my opinion it is more
natural to use INTEGER because you are dealing only with whole
numbers. The range of numbers you need to represent is limited. You
need to represent those numbers exactly. I tend to use the minimal
data type that will do the job.
REAL numbers are really floating point numbers. While some values are
exact, most are actually only approximate values.
For example, Fortran has COMPLEX. You can do calculations on REALs
using COMPLEX, just set the imaginary part to 0, but why make things
more "complex" than you need to?
A web search on Fortran data types should make you more familiar with
their characteristics.
- e
[sorry newsgroup for google posting :-)]
This will speed his search: http://en.wikipedia.org/wiki/Fortran_language_features
Regards,
Mike Metcalf
> Using this principle, no fancy formulas and such ...
If, on the other hand, you prefer fancy formulas, looking up
"fibonacci" in Wikipedia is a good start. Changes the complection
of the problem completely.
--
write(*,*) transfer((/17.392111325966148d0,6.5794487871554595D-85, &
6.0134700243160014d-154/),(/'x'/)); end
> You do NOT need recursion to solve this problem.
... unless it's a requirement of the class assignment that
a recursive approach is used.
#Paul
Although conceptually recursive calculation of the Fibonacci numbers
is simple, you must be aware that the recursion can very quickly cause
the computer to run out of memory. People with better knowledge of
compilers please correct me if I'm off base.
If Fib(N) is the N-th number in the Fibonacci sequence, the well known
formula
Fib(N+1) = Fib(N) + Fib(N-1) for N > 1
means that when function Fib is used, it calls it self twice. Each of
this two invocations calls Fib twice, each of which calls it self
twice, ... As you can see, to using a recursive function to calculate
Fib(N) causes Fib to invoke itself roughly 2**N times. So if you want
to calculate Fib(64) with the recursion, your 64-bit computer might
saturate its address space.
HTH.
Jomar
On the problem of deciding whether to use REAL or INTEGER types, I
have developed what I call the three-and-three-quarter test: if 3 3/4
is a sensible value, then use REAL, otherwise INTEGER. For example,
page 3 3/4 of a book makes no sense.
Dave Flower
That is true, but if you use a technique called memoizing,
you can cut off the ever-spreading branches of the tree, leaving
only the trunk.
Fib(4) needs Fib(2) and Fib(3)
Fib(2) needs Fib(1) and Fib(0) (both known already),
(Fib(2) is now known and can be stored.)
Fib(3) needs Fib(1) and Fib(2) - thanks to the memoization,
Fib(2) does not need to be computed again, so the recursion
ends there.
And so on.
Regards,
Arjen
In that case it still is instructive and not difficult to write a non
recursive version first. If the assignment had been "Program the Towers of
Hanoi Puzzle", then I would not assign it to an introductory class without
recursion. I would leave the non recursive version for a more advanced class
with some background in data structures.
-- Elliot
And so on.
Regards,
Arjen
---> Interesting. But not as a problem in an introductory course. [Back in
my college days, we had ALGOL, so the playing field is a bit different. :-)]
It is time for review of CompSci 101!
Think of the calling tree. There will be many repetitions in the
terminal leaves. To deal with that one uses tabling of previously
visited leaves to improve efficiency. But the whole tree is never
active at once. Just a path to the terminal node. The amount
of memory required is the maximal tree depth as this will be
a depth first traversal of the tree. (Quicksort does the shorter
of its two subproblems first to keep the tree shallow.)
If the tree traversal was a breadth first search then the number of
active nodes would go up. The old program that did a stress test of
a multiprogramming operating system by submitting two copies of itself
would be a fine example of a breadth first process. A nice way to
overflow the input queues (and seriously annoy the sysadmin).
Depth first tends to use less momory as it uses a stack.
Breadth first tends to use more memory as it uses a queue. Both
can benefit from tabling of already known results. In examples
that are not trivial the tree is not well known in advance so
the choice may not be so obvious.
> Although conceptually recursive calculation of the Fibonacci numbers
> is simple, you must be aware that the recursion can very quickly cause
> the computer to run out of memory. People with better knowledge of
> compilers please correct me if I'm off base.
> If Fib(N) is the N-th number in the Fibonacci sequence, the well known
> formula
> Fib(N+1) = Fib(N) + Fib(N-1) for N > 1
> means that when function Fib is used, it calls it self twice. Each of
> this two invocations calls Fib twice, each of which calls it self
> twice, ... As you can see, to using a recursive function to calculate
> Fib(N) causes Fib to invoke itself roughly 2**N times. So if you want
> to calculate Fib(64) with the recursion, your 64-bit computer might
> saturate its address space.
Well, no. The compiler would have to spawn a new thread for each
invocation of Fib for this to happen in the first place, and in the
second place the number of invocations grows more like phi**n, not
2**n. For calculating Fib(64) there wouldn't in practice ever be
more than about 64 (depending on termination condition) instances
of Fib active simultaneously.
> In that case it still is instructive and not difficult to write a non
> recursive version first. If the assignment had been "Program the Towers of
> Hanoi Puzzle", then I would not assign it to an introductory class without
> recursion. I would leave the non recursive version for a more advanced
> class with some background in data structures.
My understanding of the recursive solution is that it only works to
move a complete tower from one peg to another. The non-recursive
method can assemble a complet tower from an arbitrary allowed
starting configuration. I posted both kinds of code here once,
but don't have time to look it up just now.
It is possible that this feature of the straightforward recursive
solution was the goal of the original homework assignment. And
there are several other lessons that could be learned from such an
implementation.
$.02 -Ron Shepard
I probably should use the recursive solution, just because that's what
the teacher suggested. I think I could do it using another method but
it would only be able to work with lower values of N, whereas I need
this to work with any given value of N. So recursion is probably my
best bet, but for me its a more complicated method that I haven't
really learned much about. She tends to do that, she gives us
homework on something and then doesn't teach us how to do it until
after. I'm not sure if its intentional or if the syllabus is wrong but
she doesn't really seem to have an answer for us. Like right now, I'm
in class and we are learning about binary searches, yet our homework
that is due friday night is supposed to be done with recursion. See
why I'm so confused?
>"Luka Djigas" <ldigas@remove_this.gmail.com> wrote in message
>news:36tkh4hapd0pp6p4c...@4ax.com...
>
>> Using this principle, no fancy formulas and such ...
>
>If, on the other hand, you prefer fancy formulas, looking up
>"fibonacci" in Wikipedia is a good start. Changes the complection
>of the problem completely.
Of course.
But it still leaves the problem of having a numberE+308 in size.
Funny, until now I didn't know fortran knew the concept of "Infinity".
-- Luka
See this web page http://www-teaching.physics.ox.ac.uk/Unix+Prog/hargrove/tutorial_90/08_subprograms.html
near the bottom is a listing of a recursive factorial FUNCTION. Your
project involves writing a SUBROUTINE. But this might help you see how
to do recursion in Fortran 90+.
Presumably your course has covered the difference between SUBROUTINEs
and FUNCTIONs.
Binary search of a list can be done with or without recursion. For a
binary search tree, recursion is easier.
--- elliot
> Funny, until now I didn't know fortran knew the concept of "Infinity".
That came into the Fortran standard with the rest of the IEEE stuff. Of
course, particular compilers have had it for far longer (the CDC
machines I worked on starting in 1973 had it), but as of f95+IEEE TR, it
is in the Fortran standard.
--
Richard Maine | Good judgment comes from experience;
email: last name at domain . net | experience comes from bad judgment.
domain: summertriangle | -- Mark Twain
you would think...but no, our teacher has not yet covered SUBROUTINEs,
so I have no idea how to do this method. I think I could do the
problem with a DO LOOP but that won't help here, she wants us to use a
recursive subprogram :( I wish she would teach us before we had
homework on something, and the book doesn't help because none of the
samples show the answers and there's no actual code in the book. It
basically talks about definitions of things, but without actually
seeing some ACTUAL CODE I'm just lost on this.
>
> Binary search of a list can be done with or without recursion. For a
> binary search tree, recursion is easier.
>
> --- elliot
all the more reason you would think she would teach recursion first,
but no...this class sucks
I can really use some more help here, thanks so for for what all of
you have given me. But, I need to use recursion so I can't really use
all the simpler methods. I have a hard time understanding this stuff
without seeing some code.
I know I need to add (N-1) + (N-2) somehow. I'm confused about how to
use fib(N) so that when I type N it knows I mean the Nth term in the
series, not the number N. I'm also confused about how to get the
program to keep updating the values on its own without having to
completely type out the entire series, without just using a DO LOOP.
How can I code this series using recursion?
Thanks everyone!
If you use a recursive function, code is rather straight forward. A
recursive function has the property that it can invoke itself. So if
you have
recursive function fib(N) result(F)
! FIB(N) returns the N-th number in the Fibonacci sequence
integer N
integer(selected_int_find(18)):: F ! allow for larger integers
:
end function fib
The body of the function is allowed to have the well-known recursion
F = fib(N-1) + fib(N-2)
You also need an if statement for the exit condition. I.e. an "if" to
find out when not to use the recursion above.
Beware that without the memoization mentioned by Arjen and others, the
execution time of the simple recursion grows exponentially with N.
Best luck,
Jomar
---------> The problem here is that in order to USE RECURSION, you have to
create a SUBPROGRAM which then calls itself - until finally it does not call
itself any more.
I don't see how you can do recursion with just a main program.
I think I could do the
problem with a DO LOOP but that won't help here, she wants us to use a
recursive subprogram :( I wish she would teach us before we had
homework on something, and the book doesn't help because none of the
samples show the answers and there's no actual code in the book. It
basically talks about definitions of things, but without actually
seeing some ACTUAL CODE I'm just lost on this.
A DO loop is fine. There are two forms. DO with an index variable (usually)
preforms a block of code a set number of times. DO ... END DO performs a
block of code until some statement inside the loop causes it to exit. I'll
skip DO WHILE and WHILE DO, I don't use them.
You need to generate 8 Fibonacci values. So a program skeleton would be:
program fibonacci
implicit none
integer i
... more variable declarations ...
... initialize variables here
do i=1,8
... more stuff ...
end do
end program fibonacci
-----------------------
>
> Binary search of a list can be done with or without recursion. For a
> binary search tree, recursion is easier.
>
> --- elliot
all the more reason you would think she would teach recursion first,
but no...this class sucks
I can really use some more help here, thanks so for for what all of
you have given me. But, I need to use recursion so I can't really use
all the simpler methods. I have a hard time understanding this stuff
without seeing some code.
I know I need to add (N-1) + (N-2) somehow. I'm confused about how to
use fib(N) so that when I type N it knows I mean the Nth term in the
series, not the number N. I'm also confused about how to get the
program to keep updating the values on its own without having to
completely type out the entire series, without just using a DO LOOP.
How can I code this series using recursion?
Thanks everyone!
Since you are determined to use recursion, I will think about this for a
while. Most probably I will post a non-recursive version.
-- elliot
> I wish she would teach us before we had
> homework on something, and the book doesn't help because none of the
> samples show the answers and there's no actual code in the book.
If your teacher isn't teaching the material and the book isn't any good,
it sounds to me like the only practical solution is to get another book
as a supplement. There are plenty of books on Fortran. At least some of
them are "good".
Trying to learn the language solely by posting questions here isn't
practical. This venue works ok for clarifications of specific questions,
but not as a way to learn the whole language.
There are a few online sites with the basics (such as Metcalf's
wikipedia article on Fortran language features), but I'd hate to try to
learn the language that way; it's more in the nature of reference
material than tutorial.
I realize this all doesn't help much in terms of finishing a homework
assignment by Friday. That's a hard one. (Boy, glad I went back and
reread this para; my first draft said "That's tough", which might
technically say the same thing, but colloquially implies a harsh
indifference that I did not at all intend). Well, actually doing the
Fibonacci code could be a 5-minute job; it's learning the material in
that time frame, particularly if you don't yet even have a decent
tutorial text, that is tough.
I don't think I'm up to doing an ab initio explanation of recursive
functions as a usenet posting when you haven't even seen what
subroutines and fuinctions are in the first place. That's way too much
like writing a textbook (been there) than like answering questions.
> If you use a recursive function, code is rather straight forward. A
> recursive function has the property that it can invoke itself. So if
> you have
(snip)
> The body of the function is allowed to have the well-known recursion
> F = fib(N-1) + fib(N-2)
(snip)
> Beware that without the memoization mentioned by Arjen and others, the
> execution time of the simple recursion grows exponentially with N.
That is why Fibonacci makes a poor choice for recursion.
Factorial is also a common recursion example, though at
least not exponential like Fibonacci, it is still
better done without recursion.
The only problem that I can think of that really works done
with recursion better than without it is the recursive
descent method of writing compilers. Any problem that
directly and only calls itself is probably better done
without recursion.
Otherwise,
j=0
k=1
do i=1,46
print *,k
l=j+k
j=k
k=l
enddo
end
(It worked on the first try, except for experimentally
determining the value 46. I had 100 at first.)
I hope that doesn't satisfy the OP's assignment, though.
-- glen
> How can I code this series using recursion?
A bit of a nit: I think you want to be saying "sequence" instead of
"series." The individual terms might be calculated by adding, but the sum
will diverge like any infinite collection of numbers greater than one.
An excellent resource for this is Dr. Sloane's encyclopedia of integer
sequences, where fibonacci is:
http://www.research.att.com/~njas/sequences/A000045
Dr. Sloane's attitude is that this encyclopedia is here to stay, and I
obtained my own little piece of immortality with another growth sequence:
http://www.research.att.com/~njas/sequences/A084386
Not only will they graph these sequences, you can listen to them too.
--
George
Faith crosses every border and touches every heart in every nation.
George W. Bush
Picture of the Day http://apod.nasa.gov/apod/
OK.
1. Partial apology to the OP. A non-recursive solution is not terribly
helpful in generating a recursive one, so I will post my non-recursive
program, seeing that it does not meet the criteria of the assignment.
[In another reply, Glen has written his version. There are many ways
to write the program.]
---- non-recursive ---
program fibonacci
implicit none
integer i,na,nb,nc
na=0
nb=1
do i=1,8
print *,na ! first
nc=na+nb ! next=first+second
na=nb ! new first = old second
nb=nc ! new second = old next
end do
end program fibonacci
----- end text ----
I've set the number of values to generate to 8. You can easily modify
it to input an integer N as the upper limit of the DO loop.
Now at the bottom of the page I referenced before
http://www-teaching.physics.ox.ac.uk/Unix+Prog/hargrove/tutorial_90/08_subprograms.html
Is a driver program and a sub program that computes Factorial
recursively.
The driver program inputs one value of N and computes one factorial. I
wrote a different driver which computes the first N+1 factorials given
N. fact(0) == 1.
Here the subprogram is an internal procedure. I'm not going to explain
what an internal procedure is here. The advantage is that you don't
need the interface part as listed on the original page.
So here is my driver plus their subroutine:
----- start text ----
! The driver program is mine
PROGRAM Compute_Factorial
IMPLICIT NONE
INTEGER :: N, I
WRITE(*,*) 'enter an integer n'
READ(*,*) N
IF (N < 0) THEN
WRITE(*,*) 'n must be at least 0'
ELSE
DO I=1,N
WRITE(*,*) 'FACT[', I, ']=',Factorial(i)
END DO
END IF
CONTAINS
! This subroutine is from
! http://www-teaching.physics.ox.ac.uk/Unix+Prog/hargrove/tutorial_90/08_subprograms.html
RECURSIVE FUNCTION Factorial(n) RESULT(Fact)
IMPLICIT NONE
INTEGER :: Fact
INTEGER, INTENT(IN) :: n
IF (n == 0) THEN
Fact = 1
ELSE
Fact = n * Factorial(n-1)
END IF
END FUNCTION Factorial
END PROGRAM Compute_Factorial
---- end text ----
if you run the program, you will see how quickly factorial grows - and
overflows. You might see how the program slows down for larger values
of N.
Note that in the recursive routine you have at least one exit
condition where the function does not call itself. Also you have part
of the program where the routine calls itself.
Is Fibonacci similar to Factorial? YES. There are a number of ways to
parameterize the sequence. I am going to define the values of N to
start at 1. I'll also define F(1) = 0 and F(2) = 1. You know what the
definition of F(n) is.
Go to it!
Modify the program so that it computes F(n) instead of Fact(N).
Run the program and see how quickly F(n) grows. Also for larger N it
slows down. One of the things that I hope you are expected to learn is
that this way of computing F(n) is inefficient. On my machine, it
crawls at about N=40 and up. Why? Read the discussion above about how
it works. Notice that each call to F(n) output only ONE value. While
it computes all intermediate values needed, it stores none of them for
re-use and it outputs none of them in the process.
HTH.
[I learned something in the process, so I don't feel the time I took
to write a fairly detailed "lesson" is wasted.]
-- elliot
[There is a BUG in my Factorial driver, I'll let you fix it for
Factorial. It's OK for F(n)].
/* NG members - I did not do this student's homework! */
thanks a lot, the factorial example really helps. at least now I can
see what recursion does, and i see why your saying it gets slow. as to
people saying I should by another book and not try to figure stuff out
on here:
this is my first time using this site. its my first time using anyone
for help. I've made it through 11.5 weeks now out of a 15 week
semester without too much of a problem. It's a introductory course
and I don't have to take any beyond it on programming. I did fine up
to this point with learning earlier programs such as IF-ELSE, DO LOOP,
CASE SELECT, etc., but its now getting a little too complicated for me
to do on my own. At this point I don't have the time to teach myself
the entire language, that is not the goal of this introductory course,
its just supposed to give me a background if I decide to continue with
it (which I'm not). I'm just trying to get through the the last 4
weeks of class.
thanks again elliot and everyone else who has been helping me,
bobby
p.s. i need to finish a paper now for my political science class about
the election, so I'll prob work on this program tomorrow afternoon/
night. I'll post my code on here when I'm done, hopefully it will
help someone else in the future and you guys will be able to catch my
mistakes so others don't make them too
Here's what I came up with, and it works...thanks everyone!!! This
actually really helped me understand it.
PROGRAM Fibonacci_series
IMPLICIT NONE
INTEGER :: a, i
WRITE(*,*) 'Please enter a term at which to stop'
READ(*,*) a
IF (a < 0) THEN
WRITE(*,*) 'a must be positive integer'
ELSE
DO I=1,A
WRITE(*,*) Fibonacci(I)
END DO
END IF
CONTAINS
RECURSIVE FUNCTION Fibonacci(b) RESULT(FBN)
IMPLICIT NONE
INTEGER :: FBN
INTEGER, INTENT(IN) :: b
IF (b == 1) THEN
FBN = 0
ELSE IF (b == 2) THEN
FBN = 1
ELSE
FBN = Fibonacci(b-2) + Fibonacci(b-1)
END IF
END FUNCTION Fibonacci
END PROGRAM Fibonacci_series
"Bobbyj124" wrote:
> thanks a lot, the factorial example really helps. at least now I can
> see what recursion does, and i see why your saying it gets slow. as to
> people saying I should by another book and not try to figure stuff out
> on here:
Here's what I came up with, and it works...thanks everyone!!! This
CONTAINS
RECURSIVE FUNCTION Fibonacci(b) RESULT(FBN)
END FUNCTION Fibonacci
END PROGRAM Fibonacci_series
---> Great. I'm happy to see you solved the problem. Thanks for coming back
and posting your program code. It really helps keep me motivated to answer
student questions when I see signs of their work, learning, and in this case
success.
-- e
recursion still hurts my head tho
>
> -- e
>
>
--
Gary Scott
mailto:garylscott@sbcglobal dot net
Fortran Library: http://www.fortranlib.com
Support the Original G95 Project: http://www.g95.org
-OR-
Support the GNU GFortran Project: http://gcc.gnu.org/fortran/index.html
If you want to do the impossible, don't hire an expert because he knows
it can't be done.
-- Henry Ford
Mine too. But I once wrote a program to create, search and then traverse a
binary tree in GW-Basic. I forgot how long it took me to write and debug the
program, even with a copy of Knuth at hand. Part of the pain was using
arrays instead of pointers.
So I'll bet it is easier to write such a program in Fortran using recursion.
If it uses pointers, then my head still may hurt. :-<.
-- e
Jan