[英]C/CPP - Converting floating point arithmetic to integer arithmetic
I have the following c++ functions (implementing Bresenham's line algorithm ), seen in the book我有以下 c++ 函数(实现Bresenham 的线算法),在书中看到
Computer Graphics From Pixels to Programmable Graphics Hardware By Alexey Boreskov, Evgeniy Shikin从像素到可编程图形硬件的计算机图形 作者 Alexey Boreskov, Evgeniy Shikin
One of the function uses floats, and due to their inefficiency the book has presented another function which uses integer arithmetic only.其中一个 function 使用浮点数,由于效率低下,本书提出了另一个 function 仅使用 integer 算术。
I'm having trouble understading why are the two equivalent, and why are we using left shift <<
here, doesn't a<<1
simply multiply a
by 2?我很难理解为什么这两个是等价的,为什么我们在这里使用左移<<
, a<<1
不是简单地将a
乘以 2 吗?
Note : We assume the points A:(xa,ya)
and B:(xb,yb)
have integer values.注意:我们假设点A:(xa,ya)
和B:(xb,yb)
具有 integer 值。
void drawLine(int xa, int ya, int xb, int yb, int color) {
float k = (float)(yb-ya)/(float)(xb-xa);
float d = 2*k - 1
int y = ya;
putPixel(xa, ya, color); // paint the pixel (xa,ya) in color "color"
for (int x = xa+1; x<=xb; x++) {
if (d > 0) {
d += 2*k + 2;
y++;
} else {
d += 2*k;
}
putPixel(x, y, color);
}
}
void drawLine(int xa, int ya, int xb, int yb, int color) {
int dx = xb - xa;
int dy = yb -ya;
int d = (dy<<1) - dx;
int d1 = dy <<1;
int d2 = (dy - dx) << 1;
int y = ya;
putPixel(xa, ya, color); // paint the pixel (xa,ya) in color "color"
for (int x = xa+1; x<=xb; x++) {
if (d > 0) {
d += d2;
y++;
} else {
d += d1;
}
putPixel(x, y, color);
}
}
The floating-point code does four things with d
:浮点代码对d
做了四件事:
d
to 2 dy / dx −1, where dy and dx are yb
− ya
and xb
− xa
, respectively.将d
初始化为 2 dy / dx -1,其中dy和dx分别是yb
- ya
和xb
- xa
。d
is greater than 0.评估d
是否大于 0。d
.将 2 dy / dx +2 添加到d
。d
.将 2 dy / dx添加到d
。In floating-point, the division by dx may produce a non-integer.在浮点数中,除以dx可能会产生非整数。 To avoid this, we transform the operations by multiplying everything by dx , yielding:为了避免这种情况,我们通过将所有内容乘以dx来转换操作,得到:
d
to 2 dy − dx .将d
初始化为 2 dy - dx 。d
is greater than 0 dx (equal to 0).评估d
是否大于 0 dx (等于 0)。d
.将 2 dy +2 dx添加到d
。d
.将 2 dy添加到d
。 We can readily see that these four equivalent operations are implemented in the integer code except for 3. The integer code appears to add 2 dy −2 dx to d
.我们可以很容易地看到这四个等效操作在 integer 代码中实现,除了 3。integer 代码似乎将 2 dy -2 dx添加到d
。 The integer code matches code shown in the Wikipedia page for Bresenham's line algorithm . integer 代码与Wikipedia 页面中显示的 Bresenham 线算法代码相匹配。 I suspect the +
in the floating-point version is an error in the book.我怀疑浮点版本中的+
是书中的错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.