Almost all ray tracing programs have a routine that creates an orthonormal basis from a unit vector n. I am messing with my Swift ray tracer and just looked around for the "best known method". This routine is always annoyingly inelegant in my code so I was hoping for something better. Some googling yeilded a lovely paper by Jeppe Revall Frisvad. He builds the basis with no normalization required:
It's not obvious, but those are orthonormal. The catch is the case where 1-nz = 0 so unfortunately an if is needed:
Still even with the branch it is very nice. I was hoping that a careful use of IEEE floating point rules would allow the branch to be avoided but I don't see it. But perhaps some clever person will see a reconstructing. The terms 0*0/0 should be a zero in principle and then all works out. The good news is that for n.z near 1.0 the stability looks good.