In the derivative.cpp example it first computes derivative w.r.t force, then velocity, and finally qpos. Care was taken to make sure quaternions are differentiated correctly but I believe an indexing error remains if you have a model with quaternions (m->nq != m->nv). In the worker function where the derivative w.r.t qpos is calculated: // finite-difference over position: skip = mjSTAGE_NONE for( int i=istart; i<iend; i++ ) <- iterating over m->nv { /.../ d->qpos += eps; <- I believe the index should be in terms of qpos indices so I changed this to this d->qpos[m->jnt_dofadr[jid]] += eps; and now I get the correct FD matrix.
You are right, there is an indexing bug in that code which I also discovered recently. The code sample in the documentation is now updated. The correct correction is: d->qpos[m->jnt_qposadr[jid] + i - m->jnt_dofadr[jid]] += eps; The extra offset is needed because for free joints we have 3 translational dofs for the same jnt_qposadr.