On a side note, this is why geometry operations (and particularly reprojections/etc) are sometimes best treated like cryptography: "don't roll your own, use a library".
It's not an absolute, by any means, but a GEOS/etc dependency is often well worth the pain of getting spatial operations correct.
That having been said, I've made very similar mistakes embarrassingly recently...