快速找到以2为底的对数的整数部分 [英] quickly find the integer part of the base 2 logarithm

查看:104
本文介绍了快速找到以2为底的对数的整数部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是计算浮点数以2为底的对数的整数部分的有效方法?像

What is an efficient method to calculate the integer part of the base 2 logarithm of a floating point number? Something like

N = ceil( log2( f ))

N = floor( log2( f ))

对于浮点f.我猜这可能以某种方式非常有效地实现,因为可能只需要访问浮点指数即可.

for floating point f. I guess this is possible to realize very efficiently somehow as one probably only needs access to the floating point exponent.

我对精确度并不主要感兴趣.我可以容忍+ -1的错误.我以列举两个变体为例,因为一个变体在计算上可能比另一个变体便宜(但我不知道).

I am not primarily interested in exactness. I could tolerate an error of +-1. I listed the two variants just as an example because one might be computationally cheaper than the other (but I dont know).

我需要此参数来精确控制算法,其中参数f是一定的容差,并且需要对数来控制项数.日志的准确计算并不重要.

I need this for accuracy control of an algorithm where the parameter f is some tolerance and the log is needed to control the number of terms. Accurate calculation of the log is not important.

这与要求整数参数的log2的许多其他问题不是重复的(例如,

this is not a duplicate of other the many other questions asking for the log2 of an integer argument (e.g. How to do an integer log2() in C++?) . This here is about floating point argument and a completely different story. Specifically I need it for f < 1, which is not possible at all with the integer methods

推荐答案

标准库函数

The standard library function frexp does exactly that: it decomposes a double into an integer exponent and a normalized mantissa.

如果您满意对数的下限,而不是将对数舍入到最接近的整数,则最好使用较新的标准库函数

If you are content with the floor of the logarithm, rather than rounding the logarithm to the nearest integer, you are probably better off with the newer standard library function ilogb.

请注意,这两个函数对零和无穷数的处理方式不同,因此它们并不是可互换的.

Note that these two functions treat zeros and infinities differently, so they are not quite interchangeable.

这篇关于快速找到以2为底的对数的整数部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆