How about other languages (and compiler systems)?
Are there binary tricks worth knowing about to quickly calculate reciprocals?
How about other languages (and compiler systems)?
Are there binary tricks worth knowing about to quickly calculate reciprocals?
However, when we enable `-ffast-math`, we permit the compiler to do a bit more aggressive optimization in this domain (trading off precision), and we see multiplication (mulss) is emitted: https://godbolt.org/z/KEb1nc43z
Yes! You can calculate an approximate reciprocal with a single subtraction and some type-casting or bit manipulation.
The accuracy isn’t great (relative error of up to ~5%), but it might be good enough for many applications. The method is famous for being used to normalize 3d vectors in Quake https://en.wikipedia.org/wiki/Fast_inverse_square_root
This same method for calculating 1/x^2 can also be used to calculate 1/x by using a different magic constant and skipping the shift-right by one bit.