Propagation of charged particle inside a set of magnets

I am trying to find the equations of a charged particle inside a dipole & quadripole. Practically, I need to write a simulation program for it which assumes a beam passing through a dipole-quadripole-dipole which are setting around an arc. Is there some recommended literature ? Of course, I am not just interested into the classical relation of calculating the radius of the bended particle, rather than the px,py, exiting_angle etc-. For instance, I found in some outdated code, that costheta = q/sqrt(px*px+1) but could not find how to derive this formula.