不明白nextpow的工作原理

发布于 2025-02-12 04:09:46 字数 648 浏览 2 评论 0原文

最近,我一直在研究nextPow(a :: Real,x :: real)函数在内部工作。该代码在Julia项目的base/intfuncs.jl中。对于情况a == 2有一个优化,因为它很常见。

a == 2 && isa(x, Integer) && return _nextpow2(x)

但是,我不明白这种情况是如何工作的,我知道这种对位的操纵必须是找到下一个a^n的常见的东西,但是现在我不明白。

_nextpow2(x::Unsigned) = oneunit(x)<<((sizeof(x)<<3)-leading_zeros(x-oneunit(x)))
_nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_nextpow2(unsigned(-x)) : _nextpow2(unsigned(x)))

特别是我不明白的是函数_nextPow2(x :: unsigned)。为什么这有助于获得a^n大于x

Recently I have been looking at how the nextpow(a::Real, x::Real) function works inside. The code is in base/intfuncs.jl of the Julia project. For the case a == 2 there is an optimization as it is very common as case.

a == 2 && isa(x, Integer) && return _nextpow2(x)

However, I don't understand how this case works, I understand that this manipulation of bits must be something common to find the next a^n, but right now I don't understand it.

_nextpow2(x::Unsigned) = oneunit(x)<<((sizeof(x)<<3)-leading_zeros(x-oneunit(x)))
_nextpow2(x::Integer) = reinterpret(typeof(x),x < 0 ? -_nextpow2(unsigned(-x)) : _nextpow2(unsigned(x)))

In particular what I don't understand is the function _nextpow2(x::Unsigned). Why does this help to get a^n larger than x?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为一人 2025-02-19 04:09:46

对于无符号的int,无论其bitstring()0000000001xxxxxxx,2的下一个功率只是将1放在最后一个领先0并用0000000替换整个1xxxxxx

julia> function f(x)
           @show bitstring(x)
           oneU = oneunit(x)
           Nbits = sizeof(x)<<3 # Nbits = Nbytes * 8
           Nzeros = leading_zeros(x - oneU)
           @show oneU
           @show Nbits
           @show Nzeros
           res = oneU <<(Nbits-Nzeros)
           @show bitstring(res)
           res
       end


julia> f(UInt16(18))
bitstring(x) = "0000000000010010"
oneU = 0x0001
Nbits = 16
Nzeros = 11
bitstring(res) = "0000000000100000"
0x0020

for an unsigned Int, whatever its bitstring() is, say 0000000001xxxxxx, the next power of 2 is just put a 1 at the last leading 0 and replace the entire 1xxxxxx with 0000000

julia> function f(x)
           @show bitstring(x)
           oneU = oneunit(x)
           Nbits = sizeof(x)<<3 # Nbits = Nbytes * 8
           Nzeros = leading_zeros(x - oneU)
           @show oneU
           @show Nbits
           @show Nzeros
           res = oneU <<(Nbits-Nzeros)
           @show bitstring(res)
           res
       end


julia> f(UInt16(18))
bitstring(x) = "0000000000010010"
oneU = 0x0001
Nbits = 16
Nzeros = 11
bitstring(res) = "0000000000100000"
0x0020
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文