For what it’s worth, the Swift standard library already includes a method called _binaryLogarithm() in the BinaryInteger protocol.
It is underscored, hence not meant for public use, but it does exist.
For what it’s worth, the Swift standard library already includes a method called _binaryLogarithm() in the BinaryInteger protocol.
It is underscored, hence not meant for public use, but it does exist.
in game development, expectations for portability are a bit different than one might have in other areas of computer engineering. i imagine the tutorial author was likely taking a shortcut to focus on teaching the texturing API.
It’s not a shortcut, it’s mathematically and conceptually correct. It’s just not resilient to a low-quality implementation of log2. It’s reasonable to expect the authors of log2 to understand floating-point corner cases.
If you only want the integer part of log2(x) for a floating-point number, then frexp seems like a good choice, since it yanks it directly out of the bit representation and you don't need to worry about the cost or accuracy of computing a log.
In the motivating use case, all the math can be done with integers. There would be no need to round-trip through floating point except for the lack of an integer log2().
Ah, in that case I could definitely get behind having a standard function to do sizeof(T)*CHAR_BIT - ctlz(x) - 1 and call it floorLog2 or something else easy to find.
Is that what the _binaryLogarithm() method that @Nevin found does? I actually quite like that name. (I acknowledge this is a tangent and should be broken out to its own thread.)
Yes. Source: me—I put it there originally.
Note that it was genuinely meant for internal consumption (to implement parts of SE-0067), and also that both implementation details and function signatures have been tweaked since.