Taking a quick look at the code, it looks like there is a possibility of division by zero. For example, if $a=2, then it is possible that $px1=-2, and thus x1=2, which leads to a 0^-2 later on. This might be what's causing the problem.
If you have the random seed for which you get the error, you can debug it somewhat by displaying the values of the variables to the screen.