2

I'm trying to add up a large number but it's not coming out correctly.

var searchSpace = 36;
var length = 11;
var combinations = 0;

for(var i = 1; i <= length; i++) {
    combinations += Math.pow(searchSpace, i);
}

The variable combinations ends up being 135,382,323,952,046,190 which is not quite correct. It should be 135,382,323,952,046,196 (how is it off by 6?!) Any ideas?

Aaron
  • 10,386
  • 13
  • 37
  • 53
  • 2
    A good explanation of "Javascript doesn't have 'integers' - only floating point numbers": https://developer.mozilla.org/en/JavaScript/A_re-introduction_to_JavaScript#Numbers – paulsm4 Jun 15 '12 at 04:21

2 Answers2

7

JavaScript uses IEEE-754 64-bit doubles as its number format. These cannot represent arbitrarily precise values; they become incorrect when you exceed a certain threshold and begin instead storing values that are close to (but not quite exactly) the actual values. According to this earlier answer, the largest value that can be stored accurately is 253, which is about 9 × 1015. Your number (which is about 1.3 × 1017) is larger than this, so (with good probability) it cannot be represented accurately.

If you want to get the exact answer in JavaScript, you will need to use a library that supports arbitrary-precision integers. A quick Google search turned up this library, but I can't vouch for how accurate it is.

Hope this helps!

Community
  • 1
  • 1
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • 3
    To be exact, it can only contains up to 53 bits (about 16 decimal digits). If the calculation does not exceed this capacity at any point in time, there is no loss of precision. – nhahtdh Jun 15 '12 at 04:21
4

All numbers in Javascript are actually floating point numbers. You're dealing with very large numbers, and doing multiple manipulations on those numbers. The inherent errors in dealing with floats pile up quickly in this case, causing the "error".

Being off by 6 on a number that large is actually pretty good. You're off by only 0.000000000000004431%, roughly

Marc B
  • 356,200
  • 43
  • 426
  • 500