圆角除以2的幂 [英] Rounded division by power of 2

查看:159
本文介绍了圆角除以2的幂的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我采取从课本量化算法。我在那里的东西pretty很多工作的一个点,但我得到磨削时关闭接一个错误。这就是教科书有什么看法是:

I'm implementing a quantization algorithm from a textbook. I'm at a point where things pretty much work, except I get off-by-one errors when rounding. This is what the textbook has to say about that:

按四舍五入师 2 ^ P 可以通过添加进行偏移和由对位的位置右移

Rounded division by 2^p may be carried out by adding an offset and right-shifting by p bit positions

现在,我得到的右移位,但是抵消他们在谈论什么?

Now, I get the bit about the right shift, but what offset are they talking about?

下面是我的示例code:

Here's my sample code:

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()

我检查作为位移负整数负输入似乎是依赖于实现的。

I'm checking for negative input as bit shifting a negative integer appears to be implementation-dependent.

我的输出:

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

这是在教科书中提到,我怎么可以用它来摆脱这种错误是什么偏差?

What is the offset that is mentioned in the textbook, and how can I use it to get rid of this error?

推荐答案

的转变将截断。这种转变是一个二元运算操作。我用方括号在这里表示基地:

The shift will truncate. The shift is a binary operator operating. I'm using square brackets to denote the base here:

196605[10] = 101111111111111111[2]
101111111111111111[2] >> 16[10] = 10[2] = 2[10]

要正确地进行舍入你需要做的转变前加一半的除数。

To perform correct rounding you need to add half of your divisor before doing the shift.

101111111111111111[2] + 1000000000000000[2] >> 16[10] = 110111111111111111[2] >> 16[10] = 11[2] = 3[10]

这篇关于圆角除以2的幂的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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