Search code examples
c++algorithmderivative

Computing slope in cusps in C++


it's been a while since I've handled some math stuff and I'm a bit rusty, please be nice if I ask a stupid question.

Problem: I have n couples of lines, which are saved in memory as an array of 2D points, therefore no explicit functions. I have to check if the lines on couples are parallel, and this is a pretty easy task because it's sufficient to check if their derivatives are the same.

To do this in an algorithm, I have to check the slope of the line between two points of the function (which I have) and since I don't need an extreme accuracy, I can use the easy formula:

m = (y2-y1)/(x2-x1)

But obviously this lead me to the big problem of x2 = x1. I can't give a default value for this case... how can I workaround it?


Solution

  • Another way to compare slopes in 2D is the following:

        m1 = (y2-y1)/(x2-x1)
    
        m2 = (y4-y3)/(x4-x3)
    
    as m1 = m2
    
    
    (y2-y1)*(x4-x3) = (y4-y3)*(x2-x1) if lines are parallel 
    

    This doesn't give divide by zero & is more efficient as it avoids floating point division.