I believe your error lies in the lines
if q*q1<0
p0=p1;
q0=q1;
They ought to read
if q*q1<0
p0=p;
q0=q;
The idea is to keep the signs of q0 and q1 opposite, so you set either (p1,q1) or (p0,q0) to (p,q) whichever will retain that as true while continually shrinking the interval length. You were setting (p0,q0) to (p1,q1) which would suddenly shrink the interval length to zero with the true solution off to one side.
