The content of this article is quoted from "Computer Graphics Tutorial"
Overview of Numerical Differentiation
The numerical differentiation method is shown in the figure below:
the code
void DDA_line2(int x1, int y1, int x2, int y2)
{
float increx, increy, x, y, length;
int i;
if (abs(x2 - x1) > abs(y2 - y1))
length = abs(x2 - x1);
else
length = abs(y2 - y1);
increx = (x2 - x1) / length;
increy = (y2 - y1) / length;
x = x1;
y = y1;
for (i = 1; i <= length; i++)
{
putpixel(int(x + 0.5), int(y + 0.5), RED);
x += increx;
y += increy;
}
}
Notice
The formula for calculating the slope of a straight line: K=(y2-y1)/(x2-x1), as we all know, can only be used for straight lines that are not perpendicular to the X axis, otherwise x2=x1 will cause an error of dividing by zero. So is it considered in the DDA algorithm? The answer is yes, test the DDA algorithm, DDA_line(10,0,10,100) will find that the vertical straight line is successfully generated, and no error is reported. Why is this?
Generate a straight line (x1, y1)->(x2, y2), set condition 1 as: x1≠x2, and condition 2 as: y1≠y2, then in general, at least one of condition 1 and condition 2 is established. When x1=x2, y1 is not equal to y2, so abs(y2-y1)>abs(x2-x1), so it will choose to calculate the increment Δy in the y direction to cause the transformation of x, that is, k=(x2-x1) /(y2-y1), then y is +1 or -1 each time, while x remains unchanged. Vice versa, a line perpendicular to the x-axis or y-axis can be generated.
Then when x1=x2, y1=y2, this special case will result in division by zero, but the length in the above code is of float type, dividing by length=0 will not report an error, but the type value will be: -nan (ind) . Since length=0, the loop body will not be executed once, so this point will not be generated.
improve algorithm:
void DDA_line(int x1, int y1, int x2, int y2)
{
float k, length;
if (abs(x2 - x1) > abs(y2 - y1))
length = abs(x2 - x1);
else
length = abs(y2 - y1);
float dx = (x2 - x1) / length;
float dy = (y2 - y1) / length;
float x = x1, y = y1;
putpixel(x, y, RED);
for (int i = 1; i < length ; i++)
{
x += dx;
y += dy;
putpixel(int(x+0.5), int(y+0.5), RED);
}
}
The improved algorithm above will always generate a starting point.