For example, the number of derangments of 10 objects is 10! - [C(10,1)9! - C(10,2)8! + ... -C(10,10)0!]. To implement this using a random variable $n instead of 10, I'm writing a loop:
$next = 0;
for ($j=1; $j <= $n; $j++)
{ $next = Compute("$next + (-1)^($j+1) * C($n,$j) * ($n-$j)!"); }
and then $ans = Compute("$n! - $next");
This works some times, but when $n gets large, Compute returns a real number like 6.70443E+11, which is not exactly correct. So the loop introduced rounding error (at least I think this is why I'm getting wrong answers some times).
Does anyone have any ideas how to work around this?
Thanks,
Oscar.