So, I started by trying to find the 100th Fibonacci number using a recursive function, and a memoizing function using the following code.
Function.prototype.memoize = function () { var originalFunction = this, slice = Array.prototype.slice; cache = {}; return function () { var key = slice.call(arguments); if (key in cache) { return cache[key]; } else { return cache[key] = originalFunction.apply(this, key); } }; }; var fibonacci = function (n) { return n === 0 || n === 1 ? n : fibonacci(n - 1) + fibonacci(n - 2); }.memoize(); console.log(fibonacci(100));
Now, as you can see in this script, the result is JavaScript log 354224848179262000000. The hundredth Fibonacci number actually corresponds to 354224848179261915075 according to WolframAlpha , which is correct.
Now, my question is this. Why is the number calculated incorrectly even if the algorithm is completely normal? My thoughts point to JavaScript, because according to Google calculator 1, the two numbers are equal.
What is JavaScript that causes such an error? The number is safely within the maximum value of the IEEE 754 number, which is 1.7976931348623157e + 308.
1 In case this may be a bug on my platform, I tested it on both Chromium and Firefox on Ubuntu.
source share