»
S
I
D
E
B
A
R
«
A function for creating the Fibonacci sequence with jQuery
April 20th, 2010 by neil

Here is a little function that I wrote with javascript and jQuery to iterate through all of the Fibonacci numbers that my computer was capable of generating. The computer has a maximum of 1476 interations before you just get infinity. The Fibonacci number at 1476 iterations is 1.3069892237633987e+308.

At the 1477th iteration the function is trying to add 1.3069892237633987e+308 + 8.077637632156222e+307, which is a little bit too much I guess and so all you get is ‘infinity’ as the result.

I had looked at a few other javascript functions for Fibonacci sequences before creating this one but they seemed to take forever to generate say 30-40  numbers and would just cause the browser to hang if you tried to go much higher.

So … to the code

The first part sets up the variable to be used and the array.

The function takes the current value of i and adds it to the previous one using the variable j. This new number is then appended to the array and written to screen at #fibbit which is the paragraph at the bottom.

The form lets you choose how many numbers you want to iterate through.

<script  src=”http://code.jquery.com/jquery-latest.js” language=”javascript”></script>
<script language=”javascript”>

var f = 1;
var fibrange = new Array();

fibrange[0] = 1;
fibrange[1] = fibrange[0];

function fib(x) {

$(‘#fibbit’).text(” “);
$(‘#fibbit’).append(fibrange[0]+’, ‘+fibrange[1]+’, ‘);

for (i=2; i<x; i++){
j = i-1;
k = i-2;

fibrange[i] = fibrange[j] + fibrange[k];

$(‘#fibbit’).append(fibrange[i]+’, ‘);

}

}

</script>

<p>Enter a number to generate a Fibonacci sequence and hit go.</p>

<form>

<input name=”textBox” id=”textBox” type=”text” />

<input name=”send” type=”button” id=”send” value=”go” onclick=”fib(document.getElementById(‘textBox’).value)” />

</form>

<p id=”fibbit”></p>

And that’s about it. You can see a demo of the code here (opens in a new window) .

Feel free to use the code however you like.


»  Substance: WordPress   »  Style: Ahren Ahimsa   »  Mod: labK