Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
105 lines (94 sloc) 3.02 KB
/*
MIT License
Copyright (c) 2016 Josh Walters (josh@joshwalters.com)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#include <scu/math.h>
inline double SCU_Log2(uint64_t x) {
// Characteristic (integer) part of answer
// 64 bits - 1 - number of leading zeros = floor(log_2(x))
uint64_t c = 63 - __builtin_clzll(x);
// Mantissa (fractional) part of answer
// Where c is the characteristic, then:
// Mantissa of log_2(x) = log_2((1/2^c) * x)
double m = (1 / (double)((uint64_t)1 << c)) * x;
// Quintic function to approximate log_2 in the range of [1,2]
// Has R^2 measure of 0.999999999298
m = -2.78724185851460 +
5.04836114293578*m -
3.49452869647025*m*m +
1.59527985709976*m*m*m -
0.40532929743020*m*m*m*m +
0.04349024471841*m*m*m*m*m;
return c + m;
}
inline double SCU_Log10(uint64_t x) {
// Using log change of base rule
// Log_b(x) = Log_y(x) / Log_y(b)
// Here, Log_2(10) has been precomputed
return SCU_Log2(x) / 3.32192809488736;
}
inline double SCU_Ln(uint64_t x) {
// Using log change of base rule
// Log_b(x) = Log_y(x) / Log_y(b)
// Here, Log_2(e) has been precomputed
return SCU_Log2(x) / 1.44269504088896;
}
inline uint8_t SCU_CountTrailingZeros(uint64_t x) {
if (x == 0) {
return 64;
}
#if __GNUC__
// GCC
return __builtin_ctzll(x);
#elif __clang__
// CLANG
return __tzcnt64(x);
#else
// Have to perform trailing zero count
// This can be optimized
uint8_t count = 0;
while ((x & 1) == 0) {
// Found a 0, shift and continue
count++;
x = x >> 1;
}
return count;
#endif
}
inline uint8_t SCU_CountLeadingZeros(uint64_t x) {
if (x == 0) {
return 64;
}
#if __GNUC__
// GCC
return __builtin_clzll(x);
#elif __clang__
// CLANG
return __lzcnt64(x);
#else
// Have to perform trailing zero count
// This can be optimized
uint8_t count = 0;
while ((x & 0x8000000000000000) == 0) {
// Found 0, shift and continue
count++;
x = x << 1;
}
return count;
#endif
}