Exercise 4 C3_W1

in exercise 4.3 I am getting an error in the test function “factorial() not defined for negative values” for the factorial of n-x

I am pretty sure I have not done anything wrong and I am noticing the test function in its last line sets n=15 and x=20, which I’m pretty sure is causing the problem (and I did not touch the test code apart from running it)

I am not sure what to do

The error message suggests your code in pmf_binomial() uses the “math.factorial()” function, as suggested by the instructions.

That function throws an error for factorials of negative numbers.

If you use binom(n, p).pmf(x), this error message is avoided. Apparently it has handling for negative values.

I’ll report this to the course staff, as either the instructions to use math.factorial() are incorrect, or the test case N = 15 and X=20 is invalid.

yes thank you, that fixed the problem

but just to confirm
n here is like, the number of coins being tossed for example? And x is the even of getting a specific number of heads (or tails) so x>n would be invalid because you can’t have more heads than the number of coin tosses hence invalid case

That seems reasonable.

I also tried this code as alternative to deal with the negative number. Since 0! = 1, I just checked for negative numbers. I gives that same result as binom(n, p).pdf(x).
if n-x < 0 :
n_x = 0
else :
n_x = n-x;
pmf = …divide by factorial(x) multiplied by factorial(n_x)

If-statements are generally not a good solution, because they run quite slowly and are usually not needed.