Rounding a positive number to a power of another number

Posted by Sagekilla on Stack Overflow See other posts from Stack Overflow or by Sagekilla
Published on 2010-04-24T18:45:36Z Indexed on 2010/04/24 18:53 UTC
Read the original article Hit count: 188

Filed under:

I'm trying to round a number to the next smallest power of another number. The number I'm trying to round is always positive. I'm not particular on which direction it rounds, but I prefer downwards if possible.

I would like to be able to round towards arbitrary bases, but the ones I'm most concerned with at the moment is base 2 and fractional powers of 2 like 2^(1/2), 2^(1/4), and so forth. Here's my current algorithm for base 2. The log2 I multiply by is actually the inverse of log2:

double roundBaseTwo(double x)
{
    return 1.0 / (1 << (int)((log(x) * log2))
}

Any help would be appreciated!

© Stack Overflow or respective owner

Related posts about rounding