This is elegant but in no way effective! (The double definition “recFib[n_] := recFib[n] =…” is a nice trick to give memory to a function, see “Functions That Remember Values They Have Found” in the documentation.)
(Yes, I know, there is a constant “GoldenRatio” predefined, but when using that the simplification to integers does not work … An idea anybody?) From this formula it is obvious that the term “(1 - goldenRatio)^n” vanishes for large n (its absolute value is smaller than 1). Consequently the expression
fibApprox[x_]:= GoldenRatio^x/Sqrt[5.]
serves as a good approximation - and one can see that the growth is exponential (as it should be with rabbits …)
Henrik I prefer the first option, because in the class we’re learning recursion from the functions, for example to generate the Euclidean algorithm:
Euclides[n_, 0] := n;
Euclides[n_, r_] := Euclides[r, Mod[n, r]];
In the exercise we have the plant case and the other cases that will probably generate, but Henrik in your recursion I don’t understand the part of: recFib[n_] := recFib[n] = recFib[n - 1] + recFib[n - 2]
Can you explain me more deep please. If I do recFib[4] the function do: [4-1]+[4-2] or how? I really learn more about recursion functions. Thank you.
Can you explain me more deep please. If I do recFib[4] the function do: [4-1]+[4-2] or how?
Well, that is the very basic idea of any recursion: In a first step fib[4] will be evaluated to fib[3]+fib[2]. With this the problem is not solved but reduced in its size. The documentation (“Principles of Evaluation”) says:
The Wolfram Language is an infinite evaluation system. When you enter an expression, the Wolfram Language will keep on using definitions it knows until it gets a result to which no definitions apply.
Consequently in further steps the reduction of the problem continues until a trivial case (fib[0] = 0; fib[1] = 1;) is reached.