3

Can someone please help me. I understand the equation of a line and how to solve for the zero intercept on paper, but I have trouble converting it to code. More specifically, I need to calculate the point at which a line intercepts any given X or Y coordinate with two different functions...

double CalcLineYIntercept(LINE *line, double yintercept) { }
double CalcLineXIntercept(LINE *line, double xintercept) { }

So, CalcLineYIntercept would return the X coordinate of the point where the line intercepts yintercept (not necessarily zero). I have trouble converting algebraic equations to code (and yes I understand that C++ is an algebraic language, but the code itself does not simply and isolate variables). Is there a simple way to accomplish this?

Thank you very much

Björn Pollex
  • 75,346
  • 28
  • 201
  • 283
user491232
  • 31
  • 1
  • 2
  • 1
    We require the declaration of `LINE` to answer this. Maybe also write down the formula you want to implement. – Björn Pollex Oct 29 '10 at 11:52
  • LINE is simple a coordinate of two points, doubles, x1, y1, x2, y2. y=mx+b is the equation of a line, and y2 - y1 / x2 - x1 is the slope (m), and b is the offset, but I'm not sure how to work b into the equation here, or how to write that into code. I need the n-intercept point (the intercept point for any given coordinate, not just zero) – user491232 Oct 29 '10 at 11:59
  • 1
    @user491232: Please edit your question and add the information you provided in you comment. – Björn Pollex Oct 29 '10 at 12:04
  • So you want to pass an x=(X) (or y=(Y)) and find where your line hits the adjusted axis? –  Oct 29 '10 at 12:06

2 Answers2

4
double CalcLineYIntercept(LINE *line, double yintercept) 
{ 
    dx = line->x2 - line->x1;
    dy = line->y2 - line->y1;

    deltay = yintercept - line->y2;
    if (dy != 0) { 
        //dy very close to 0 will be numerically unstable, account for that
        intercept = line->x2 + (dx/dy) * deltay;
    }
    else {
        //line is parrallel to x-axis, will never reach yintercept
        intercept = NaN;
    }
}

Reverse x and y to get the other function.

jilles de wit
  • 7,060
  • 3
  • 26
  • 50
-1

Subtract yintercept from the line's y-coordinates, then use the math you already know to solve for x when y = 0. Mutatis Mutandis for xintercept.

Marcelo Cantos
  • 181,030
  • 38
  • 327
  • 365