Monday 15 April 2013

Fibonacci - revisited


Wow, Grey Wolf continues to astound me.

He rewrote the Fibonacci JavaScript so that it builds an array and then returns the index value you wanted.
This allows for greater calculation values and no longer crashes your pc.
Negative values are a bit strange and huge numbers will more than likely return infinity.
var fibTicks = 0;

var FibonacciTerms = new Array();

 function fibonacciR(term) {

// recursive fibonacci method (the higher the number the more times the method gets called until we get to 1)

// we could use an array and iterate the array to find the value this would then be known as an iterative method.

// values greater than 30 are likely to crash javascript, for large numbers it is advised to use a language such as python using the recursive method.

fibTicks++;

if (term<=1) return term;

else return fibonacciR(term-1)+fibonacciR(term-2);

}

 function fibonacciI(n) {

// iterative method, here we are creating a loop which will determine what the next term is, append it to an array of terms until it reaches the dssired number

var neg = false;

if (n < 0) { n = n - n - n; neg = true; } // deal with negatives (we could just return an error here)

fibTicks = 0;

var i = 2; // we already have the 0th and first term so start counting from the 2nd term

FibonacciTerms = new Array(0,1); // clear the list of terms, add the 0th and 1st term

while (i <= n) { // loop through until we reach the desired term

fibTicks++;

FibonacciTerms.push(FibonacciTerms[i-1]+FibonacciTerms[i-2]); // add the term to the array

i++; // add 1 to our loop incrementor

} // end of loop

var r = FibonacciTerms[n]; // put the N’th term in to variable ‘r’

if (neg == false) return r; // exit the function giving back the number stored in ‘r’

else return r-r-r; // exit the function giving back the negative value for the number stored in ‘r’

}

Original Post Sep 2nd 2012

No comments:

Post a Comment