Home > database >  equation for non-axis-crossing linear function
equation for non-axis-crossing linear function

Time:01-13

I want to print out a line, which's points are given by the user. I use this to check if a point is on the line. (I know it can be done more efficent. Dont worry about that.)

int proportionalFactor = (x2 - x1) / (y2 - y1);
int offset = y1 - x1 * proportionalFactor;

for(int y = 0; y < 100; y  ){                         //going over
   for(int x = 0; x < 100; x  ){                      //every point
      if(y == proportionalFactor * x   offset){       //and checking if it's on the line
         printf("X");                                 //if so, mark it
      }else{
         printf(" ");                                 //if not, skip it
      }
   }
}

As you can see, I just use the normal equation for a linear function. But in two cases this does not work. Either the line is horizontal, or vertical. For every even slightly diagonal line it works. Here are pictures of how it looks in the program if that helps:

With input: 10|10, 90|90 - works fine With input: 10|10, 90|90

With input: 10|10, 10|90 - as you can see it's horizontal, although it should be vertical With input: 10|10, 10|90

Aaaand last but not least with input: 10|10, 10|90 - should be vertical line

The program crashes when I enter these values, so no picture for that case

My question is, if I can change anything in my equation to make this work and what part of the equation I interpreted wrong?

CodePudding user response:

If a line contains the points (x1, y1) and (x2, y2), an equation for the line is (yy1) / (xx1) = (y2y1) / (x2x1). Intuitively, this says the slope of the segment from (x1, y1) to a point (x, y) is the same as the slope of a segment from (x1, y1) to (x2, y2).

However, the expressions in the equation are not defined when there are divisions by zero, which occur when the line is vertical, so x1 = x2, or when x is x1. To correct this, we can multiply by (xx1) and by (x2x1). This gives us (yy1) • (x2x1) = (y2y1) • (xx1). That is also beneficial because avoiding division means we can use integer arithmetic, if all the variables involved are integers.

Thus, provided no integer overflow occurs in the arithmetic, a point (x, y) is on the line defined by (x1, y1) and (x2, y2) if and only if (y-y1) * (x2-x2) == (y2-y1) * (x-x1).

  •  Tags:  
  • Related