The issue wasn’t with the code itself, but with the expression. It should be 1/ng instead of ng.
That change makes a big difference, since using 1/ng keeps the values on a proper scale and ensures the determinant is non-zero.
After fixing it to 1/ng, it works as expected.