Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Just a Few Simple Functions

1. ## Just a Few Simple Functions

Just a few simple but useful functions I had laying around.

Given the number of minutes of audio a CD can hold, returns the corresponding data capacity in MB.
Code:
```function cd_capacity(minutes) {
return minutes * 8.7890625;
}```
The Fibonacci numbers using the formula rather than the recursive definition for a big O of 1. [FYI] The limit as n approaches infinity of fibonacci(n+1) / fibonacci(n) yields what is known as the golden ratio.
Code:
```function fibonacci(n) {
return Math.round((Math.pow((1 + Math.sqrt(5)) / 2, n) - Math.pow(-2 / (1 + Math.sqrt(5)), n)) / Math.sqrt(5));
}```
And finally, the little trick everyone knows for giving random numbers a lower bound and upper bound now just compacted into its own little tidy function.
Code:
```/*
* rand()      0 <= n < 1
* rand(10)    0 <= n < 10
* rand(4,10)  4 <= n < 10
*/
function rand()
{
var lower = 0;
var upper = 1;

if (arguments.length == 1)
upper = arguments[0];
else if (arguments.length == 2) {
lower = arguments[0];
upper = arguments[1];
}

return Math.random() * (upper - lower) + lower;
}```

• Thanks Jeff...that's Very good

• too kool for skool

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•