Search code examples
c++boostlogarithmmultiprecisionboost-multiprecision

How to take a base 2 logarithm from a boost int256_t?


So I want to take a logarithm from an int256_t.

I found this but modifying it to take sizeof int256_t did not work. It will give incorrect results: https://stackoverflow.com/a/11376759

Is there a log function in boost which supports multiprecision?


Solution

  • Without further constraints I'd write:

    Live On Coliru

    int256_t x("12345678901234567890");
    
    std::cout << "log2(" << x << ") = " << log2(cpp_bin_float_100(x)) << "\n";
    

    Prints

    log2(12345678901234567890) = 63.4206
    

    Simpler

    You don't need all that precision if you're going to round the result anyways:

    Live On Coliru

    std::cout << "log2(" << x << ") = " << log2(x.convert_to<double>()) << "\n";
    

    Ad-hoc

    A very crude form could look like:

    Live On Coliru

    template <typename T>
    static inline int adhoc_log2(T i) {
        int n = 0;
        while(i /= 2) ++n;
        return n;
    }
    

    Prints

    adhoc(12345678901234567890) = 63
    

    Lastly, indeed you could drop back down to bit-level and apply the bit-fiddling hacks in the way @SamVarshavchik suggests