开发者

Recursion in Matlab vs Java

I hacked up a recursive function in Java for a homework problem in my Stats class, that looked something like this:

public static int d (int k, int n) {
 if (n == 1) return 1;
 else if (n > k) return 0;
 else return n*d(k-1, n) + n*d(k-1,n-1);
}

I then plugged (20, 8) into this function, and got开发者_Go百科 998,925,952. My professor, however, said that this answer was wrong, and after rethinking my code over and over again, I decided to try the same thing in Matlab:

function t = d(k,n)
  t = 0;
  if n == 1
    t = 1;
  elseif n > k
    t = 0;
  else
    t = n*d(k-1, n) + n*d(k-1, n-1);
  end

This function, apparently, gave me the right answer with the above input, 6.1169 * 10^17.

This has been bugging me all day, and I have absolutely no idea why two seemingly identical programs in two different languages would give me completely different results. Can anyone help explain this?


Your Matlab routine is probably working on floating-point input, so it will compute in floating-point.

Your Java routine has integer types; 6.1169e17 is way outside the supported range, so it overflows. Try changing your types to float or double.


611692004959217300 is much larger than 2147483647 which is the integer MAX_VALUE in Java.

I got 611692004959217300 by running

function d (k, n) {
 if (n == 1) return 1;
 else if (n > k) return 0;
 else return n*d(k-1, n) + n*d(k-1,n-1);
}

console.log(d(20,8));

in Firebug.


Consider what the maximum value an int can have, which is what you've got in Java. Now consider what the maximum value a double can have, which is MATLAB's default type.


Java integers are 4 bytes in size, so the number looks too big (greater than 2^31). You should try again using "long" or "double" as datatype for your variables.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜