How to calculate fibonacci function by math formula - javascript

How to calculate fibonacci function by math formula
I have try this formula but not work:
fib(n) = ((1 + 5^0.5) / 2)^n - ((1 - 5^0.5) / 2)^n / 5^0.5
const fib=(n)=>{
return ((1+(5**0.5))/2)**n-((1-(5**0.5))/2)**n/(5**0.5)
}
Any one know how to do?Thanks.

The formula is correct you just need to put some extra ().
const fib=(n)=>{
return (((1+(5**0.5))/2)**n-(((1-(5**0.5))/2)**n))/(5**0.5)
}
for(let i = 0;i<9;i++){
console.log(fib(i))
}

First thing I'd do is define φ
var φ = (1 + 5 ** 0.5) / 2;
Then a slightly shorter form is:
var fib = (n) => (φ ** n - ((-φ) ** -n)) / (2 * φ - 1);
Because you want an integer as a result, you could also throw in the call to Math.round().

You seem to be trying to recreate Binet's Formula. You can break down the formula a little like so, such that is becomes more readable:
const fib = n => {
const alpha = 5**0.5
const beta = alpha / 2;
return (1 / alpha) * ((0.5 + beta) ** n - (0.5 - beta) ** n);
}
console.log(fib(10));

Related

JavaScript - Difference between random function results

Is there a difference between the results of Math.floor(Math.random() * x) + 1 and Math.ceil(Math.random() * x)?
Math.random() produces floating point values in the interval [0, 1) (from zero inclusive to one exclusive). This means that there is a slight difference between the two approaches:
Math.ceil(Math.random() * x) will produce integers in the interval [0, x] (from zero inclusive to x inclusive). This is because Math.ceil(0) will return a zero. Although the chance of getting that is extremely small.
function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }
const x = 10;
console.log("min:", Math.ceil(minRandom() * x));
console.log("max:", Math.ceil(maxRandom() * x));
Math.floor(Math.random() * x) + 1 will produce integers in the interval [1, x] (from one inclusive to x inclusive). This is because Math.floor(Math.random() * x) itself produces integers in the interval [0, x-1] (zero inclusive to x-1 inclusive).
function minRandom() { return 0; }
function maxRandom() { return 0.9999999; }
const x = 10;
console.log("min:", Math.floor(minRandom() * x) + 1);
console.log("max:", Math.floor(maxRandom() * x) + 1);
Yes, there's a difference.
There is a chance, albeit a very very small one, that the second version could unexpectedly return zero.
This happens if Math.random() itself returns exactly 0.0, which it legally can.

How to do to the nth power in Javascript

I have a function that I need to handle in Javascript:
equipment * ((rate/12) / ((1-(1+(rate/12))^-term)))
How do I convert it (^) into Javascript?
This is what it looks like so far:
const calculation = equipment * ((rate / 12) / ((1 - (1 + (rate / 12)) - term)));
JavaScript has an operator for it:
console.log(3 ** 5);
Try using this:
let result = Math.pow(3, 5)
//or
let result = 3 ** 5
This is equivalent to 3^5

Javascript - Get minimum integer solution of computer equation

I am having a problem trying to solve an equation in programming.
Imagine I have this line of code:
Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10;
Given x = 1000, the result is 320.
Now, how can I solve this equation given a result?
Imagine given the result 320 I want to get the minimum integer value of x that resolves that line of code.
/*320 =*/ Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10;
I am having some hard time because of the Math.Round. Even thought that expression is a linear equation, the Math.Round makes way more solutions than one for x, so I want the minimum integer value for my solution.
Note that x is a integer and if I set x = 999 the result is still 320.
If I keep lowering x I can see that 984 (atleast in Chrome 64.0.3282.186) is the correct answer in this case, because is the lowest value of x equals to 320 in that expression/programming line.
Solving the equation with the Math.round just introduces boundary conditions.
If:
Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 = 320
Then:
Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) = 32
By dividing both sides by 10. Now you have:
Math.round(expression) = 32
Which can be expressed as an inequality statement:
31.5 < expression < 32.4999..
The expression being equal to 31.5 represents one boundary, and the expression being equal to 32.499.. represents the other boundary.So solving for the boundaries would require solving for:
expression = 31.5 and expression = 32.49999...
((x / 5) + Math.pow(x / 25, 1.3))/10 = 31.5 and
((x / 5) + Math.pow(x / 25, 1.3))/10 = 32.4999
Solving these two for x will give you the range of valid values for x. Now that's just algebra which I'm not going to do :)
I guess the most reliable way that works (albeit somewhat naive) is to loop through all valid numbers and check the predicate.
function getMinimumIntegerSolution(func, expectedResult){
for(let i = 0 /*Or Number.MIN_SAFE_INTEGER for -ves*/; i< Number.MAX_SAFE_INTEGER ; i++ ) {
if(func(i) === expectedResult)
return i;
}
}
Now
getMinimumIntegerSolution((x) => Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10 , 320)
This returns what you expect, 984
Because the function defined by
f(n) = Math.round(((x / 5) + Math.pow(x / 25, 1.3)) / 10) * 10
is monotonous (in this case, increasing), you can do a binary search.
Note that I wrote the following code originally in Java, and it is syntactically incorrect in Javascript, but should hopefully be straightforward to translate into the latter.
var x0 = 0;
var x1 = 1e6;
var Y = 320d;
var epsilon = 10d;
var x = (x1 - x0) / 2d;
var y = 0;
while (Math.abs(Y - (y = f(x))) > epsilon) {
if (y > Y) {
x = (x - x0) / 2d;
} else {
x = (x1 - x) / 2d;
}
// System.out.println(y + " " + x);
}
while (f(x) < Y)
++x;
// System.out.println(Math.round(x) + " " + f(x));
Running it on my computer leaving the System.out.println uncommented:
490250.0 250000.0
208490.0 125000.0
89370.0 62500.0
38640.0 31250.0
16870.0 15625.0
7440.0 7812.5
3310.0 3906.25
1490.0 1953.125
680.0 976.5625
984 320.0
Note that the last loop incrementing x is guaranteed to complete in less than epsilon steps.
The values of x0, x1 and epsilon can be tweaked to provide better bounds for your problem.
This algorithm will fail if the value of epsilon is "too small", because of the rounding happening in f.
The complexity of this solution is O(log2(x1 - x0)).
In addition to #webnetweaver answer. If you rearrange the final equation you get a high-order polynomial (13th degree) which is difficult to solve algebraically. You can use numerical methods as Newton's method. For numerical methods in JavaScript you can use numeric.js. You also need to solve only for the lower bound (31.5) in order to find the lowest integer x because the function is monotonic increasing. See also this post on numerical equation solving in JavaScript.
Here is a solution using Newton's method. It uses 0 as initial guess. It only takes five iterations for getting the minimum integer solution.
var result = 320;
var d = result - 5;
function func(x) {
return x / 5 + 0.0152292 * Math.pow(x, 1.3) - d;
}
function deriv(x) {
return 0.2 + 0.019798 * Math.pow(x, 0.3);
}
var epsilon = 0.001; //termination condition
function newton(guess) {
var approx = guess - func(guess) / deriv(guess);
if (Math.abs(guess - approx) > epsilon) {
console.log("Guess: " + guess);
return newton(approx);
} else {
//round solution up for minimum integer
return Math.ceil(approx);
}
}
console.log("Minimum integer: " + newton(0));

I'm trying to use random function in Javascript?

var x = 1 + Math.Random() % 9;
if (x==1)
// do something
else if (x==2)
// do something else
I used this line — (1 + Math.Random() % 9) — in C++ to get a number between 1 and 9, but in JavaScript I'm getting a different result.
Math.random() returns a value between 0 and 1, so instead using the modulo operator you need to use a multiplication.
1 + (Math.random() * 9);
Finally, you should round or .floor() that value
var x = Math.floor( 1 + ( Math.random() * 9 ) );
or, shorter
var x = ~~( 1 + ( Math.random() * 9 ) );
There is no Math.Random() function in JavaScript. It's Math.random(). Note the capitalization.
To get a random number between a certain minimum and maximum value, do this:
var min = 1, max = 9;
Math.floor(Math.random() * (max - min + 1)) + min;
Further reading: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Math/random
In Javascript the Math.random function returns a number between 0 and 1. If you want to get a number between 1 and 9 you'll have to work with it a bit.
var number = ((Math.random() * 10) | 0) % 9 + 1
This will give you a result between 0 and 9
Math.floor(Math.random()*9)
And by the way, jQuery is a javascript framework. Math is a native javascript function

Javascript intelligent rounding

I currently need to round numbers up to their nearest major number. (Not sure what the right term is here)
But see an example of what I'm trying to achieve
IE:
13 // 20
349 // 400
5645 // 6000
9892 // 10000
13988 // 20000
93456 // 100000
231516 // 300000
etc. etc.
I have implemented a way of doing this but its so painful and only handles numbers up to a million and if I want it to go higher I need to add more if statements (yeah see how i implmented it :P im not very proud, but brain is stuck)
There must be something out there already but google is not helping me very much probably due to me not knowing the correct term for the kind of rounding i want to do
<script type="text/javascript">
function intelliRound(num) {
var len=(num+'').length;
var fac=Math.pow(10,len-1);
return Math.ceil(num/fac)*fac;
}
alert(intelliRound(13));
alert(intelliRound(349));
alert(intelliRound(5645));
// ...
</script>
See http://jsfiddle.net/fCLjp/
One way;
var a = [13, // 20
349, // 400
5645, // 6000
9892, // 10000
13988, // 20000
93456, // 100000
231516 // 300000
]
for (var i in a) {
var num = a[i];
var scale = Math.pow(10, Math.floor(Math.log(num) / Math.LN10));
print([ num, Math.ceil(num / scale) * scale ])
}
13,20
349,400
5645,6000
9892,10000
13988,20000
93456,100000
231516,300000
The answer from #rabudde works well, but for those that need to handle negative numbers, here's an updated version:
function intelliRound(num) {
var len = (num + '').length;
var result = 0;
if (num < 0) {
var fac = Math.pow(10, len - 2);
result = Math.floor(num / fac) * fac;
}
else {
var fac = Math.pow(10, len - 1);
result = Math.ceil(num / fac) * fac;
}
return result;
}
alert(intelliRound(13));
alert(intelliRound(349));
alert(intelliRound(5645));
alert(intelliRound(-13));
alert(intelliRound(-349));
alert(intelliRound(-5645));
you can use Math.ceil function, as described here:
javascript - ceiling of a dollar amount
to get your numbers right you'll have to divide them by 10 (if they have 2 digits), 100 (if they have 3 digits), and so on...
The intelliRound function from the other answers works well, but break with negative numbers. Here I have extended these solutions to support decimals (e.g. 0.123, -0.987) and non-numbers:
/**
* Function that returns the floor/ceil of a number, to an appropriate magnitude
* #param {number} num - the number you want to round
*
* e.g.
* magnitudeRound(0.13) => 1
* magnitudeRound(13) => 20
* magnitudeRound(349) => 400
* magnitudeRound(9645) => 10000
* magnitudeRound(-3645) => -4000
* magnitudeRound(-149) => -200
*/
function magnitudeRound(num) {
const isValidNumber = typeof num === 'number' && !Number.isNaN(num);
const result = 0;
if (!isValidNumber || num === 0) return result;
const abs = Math.abs(num);
const sign = Math.sign(num);
if (abs > 0 && abs <= 1) return 1 * sign; // percentages on a scale -1 to 1
if (abs > 1 && abs <= 10) return 10 * sign;
const zeroes = `${Math.round(abs)}`.length - 1; // e.g 123 => 2, 4567 => 3
const exponent = 10 ** zeroes; // math floor and ceil only work on integer
const roundingDirection = sign < 0 ? 'floor' : 'ceil';
return Math[roundingDirection](num / exponent) * exponent;
}

Categories