# Math Functions ## Lerp ```cpp float bit::Math::lerp(float val1, float val2, float ratio) { return val1 + ratio * (val2 - val1); } ``` ## Clamp ```cpp float bit::Math::clamp(float value, float min, float max) { return (value > max ? max : (value < min ? min : value)); } ``` ## Round ```cpp float bit::Math::round(float value) { return std::floor(value + 0.5); } ``` ## Floor Power of 2 ```cpp float bit::Math::floorPowerOf2(float value) { if(value > 1) // 32 bit twiddling { int v = (int)value; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v - (v >> 1); } else { // domains: 0, .125, .25, .5, 1 if(value == 0) return 0; if(value > 0 && value < .125) return 0; if(value >= .125 && value < .25) return .125; if(value >= .25 && value < .5) return .25; if(value >= .5 && value < 1) return .5; else return 1; } } ``` ## Ceiling Power of 2 ```cpp float bit::Math::ceilPowerOf2(float value) { if(value > 1) // 32 bit twiddling { int v = (int)value; v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v++; return v; } else { // domains: 0, .125, .25, .5, 1 if(value == 0) return 0; if(value > 0 && value <= .125) return .125; if(value > .125 && value <= .25) return .25; if(value > .25 && value <= .5) return .5; else return 1; } } ``` ## Round to Power of 2 ```cpp float bit::Math::roundPowerOf2(float value) { float ceil = ceilPowerOf2(value); float floor = floorPowerOf2(value); if(std::abs(ceil - value) < std::abs(value - floor)) return ceil; else return floor; } ``` ## Bitwise Has Any ```cpp bool bit::Math::bitwiseHasAny(unsigned int value, unsigned int filter) { return (value & filter) > 0; } ``` ## Bitwise Has All ```cpp bool bit::Math::bitwiseHasAll(unsigned int value, unsigned int filter) { return (value & filter) == filter; } ``` ## Hash from String ```cpp unsigned int bit::Math::toHash(std::string const&st) { // s[0]*31^(n - 1) + s[1]*31^(n - 2) + ... + s[n - 1] // where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation unsigned int tally = 0; for(unsigned int i = 0; i < st.size(); i++) { unsigned int pos = i + 1; char s = st[i]; double d = (double)s; tally += d * std::pow((double)31, (double)(pos - 1)); } return tally; } ```