圆2除以2的幂

mpe*_*kov 12 python bit-manipulation rounding bitwise-operators

我正在从教科书中实现量化算法.我正处于几乎可以工作的地方,除了我在四舍五入时得到一个一个错误.这就是教科书对此的评价:

2^p可以通过添加偏移和右移位p位位置来执行舍入除法

现在,我对正确的转变有所了解,但他们谈论的是什么偏移?

这是我的示例代码:

def scale(x, power2=16):
    if x < 0:
        return -((-x) >> power2)
    else:
        return x >> power2
def main():
    inp = [ 12595827, -330706, 196605, -387168, -274244, 377496, -241980, 
            -545272,  -196605, 24198,   196605,  193584, 104858, 424683,
            -40330,     41944 ]
    expect = [ 192, -5, 3, -6, -4, 5, -3, -8, -3, 0, 3, 3, 1, 6, 0, 0 ]
    actual = map(scale, inp)
    for i in range(len(expect)):
        if actual[i] == expect[i]:
            continue
        print 'inp: % 8d expected: % 3d actual: % 3d err: %d' % (inp[i], 
                expect[i], actual[i], expect[i] - actual[i])
if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

我正在检查负输入,因为位移正负整数似乎与实现有关.

我的输出:

inp:   196605 expected:   3 actual:   2 err: 1
inp:  -387168 expected:  -6 actual:  -5 err: -1
inp:  -196605 expected:  -3 actual:  -2 err: -1
inp:   196605 expected:   3 actual:   2 err: 1
inp:   193584 expected:   3 actual:   2 err: 1
Run Code Online (Sandbox Code Playgroud)

教科书中提到的偏移是什么,我如何使用它来摆脱这个错误?

qbe*_*220 9

转变将截断.转变是二元运算符运算.我在这里用方括号表示基数:

196605[10] = 101111111111111111[2]
101111111111111111[2] >> 16[10] = 10[2] = 2[10]
Run Code Online (Sandbox Code Playgroud)

要执行正确的舍入,您需要在轮班之前添加一半的除数.

101111111111111111[2] + 1000000000000000[2] >> 16[10] = 110111111111111111[2] >> 16[10] = 11[2] = 3[10]
Run Code Online (Sandbox Code Playgroud)

  • 377496/65536 = 5.760131836.这将四舍五入为6.因此预期的答案是6,而不是5.或者我误解了你的舍入是什么意思? (2认同)