0

I made a permutation and combination calculator. The code to find the factorial of a number is:

 function factorial(num){
 total=1;
 if(num==1||num==0){
  return total;
 }
 else{
   for(i=2;i<=num;i++){
   total*=i;
   }
  return total;
 }
}

Here is the code to find permutation:

  answer.innerHTML="Answer: "+factorial(n)/factorial(n-r);

If I do 55P9 my answer is .5 off. Everything works if I use Math.floor(), but I want to find the root of the problem.

shurup
  • 751
  • 10
  • 33
  • I mean nPr(55, 9). – shurup May 21 '16 at 03:17
  • 1
    this is more about how numbers work in JS, check this out: http://stackoverflow.com/questions/3072307/what-is-the-standard-solution-in-javascript-for-handling-big-numbers-bignum – omarjmh May 21 '16 at 03:23
  • 1
    gonna leave this here too, for factorial: `function factorial(num){ return num > 1 ? num * factorial(num - 1) : num; }` – omarjmh May 21 '16 at 03:24
  • It would be more efficient have a function just for permutations, then you can iterate from n-r+1 to n, since the values below that will cancel out. It might get rid of your precision errors too. – samgak May 21 '16 at 03:38

1 Answers1

3

The reason it's returning decimals is because 55 factorial (1.27 * 10^73) and 46 factorial (5.50 * 10^57) are being stored as floating point numbers since Javascript automatically treats all numbers as double precision floating point numbers. Meanwhile, since it's so large, there's a rounding error in the quotient due to the floating point approximation being only an approximation.

Double checking this in MATLAB:

>> factorial(55)/factorial(46)
ans =
2.3073e+15
>> ans - floor(ans)
ans =
0.5000
>> .5/(factorial(55)/factorial(46))
ans =
2.1670e-16
>> eps
ans =
2.2204e-16

As you can see here, MATLAB gets the same result due to the floating point precision error. Also, consequently, .5 is the absolute error expected for this calculation since it should be some power of two.