如何计算数字的2或10的最接近幂? [英] How do I calculate the closest power of 2 or 10 a number is?
问题描述
计算2或10与另一个数字最接近的幂的最有效方法是什么?例如
What is the most efficient way to cacluate the closest power of a 2 or 10 to another number? e.g.
3.5将以2的幂返回4,以10的幂返回1
3.5 would return 4 for power of 2 and 1 for power of 10
123将以2的幂返回128,以10的幂返回100
123 would return 128 for power of 2 and 100 for power of 10
0.24将以2的幂返回0.25,以10的幂返回0.1
0.24 would return 0.25 for power of 2 and 0.1 for power of 10
我只是在寻找算法,不在乎语言.
I'm just looking for the algorithm and don't mind the language.
推荐答案
n^round(log_n(x))
其中log_n是以n为底的对数.您可能必须根据定义最接近"的方式来修改round().
where log_n is the logarithm to base n. You may have to modify the round() depending on how you define "closest".
请注意,log_n(x)
可以实现为:
log_n(x) = log(x) / log(n)
其中log
是任何方便的底数的对数.
where log
is a logarithm to any convenient base.
这篇关于如何计算数字的2或10的最接近幂?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!