Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get x intercept given two points

This might be a somewhat simple question but I can not seem to get it working.

I want to find the x intercept given two points.

Lets say I have these two points: (5,3) and (3,4) I would like to find the x intercept. Currently this is what I have. Which finds the y intercept correctly. In this case 5.5.

var A = [5, 3];
var B = [3, 4];

function slope(a, b) {
    if (a[0] == b[0]) {
        return null;
    }

    return (b[1] - a[1]) / (b[0] - a[0]);
}

function intercept(point, slope) {
    if (slope === null) {
        // vertical line
        return point[0];
    }

    return point[1] - slope * point[0];
}

var m = slope(A, B);
console.log(m);

var b = intercept(A, m);
console.log('intercept: ' + b);
like image 484
Sigmundur Avatar asked Sep 02 '26 12:09

Sigmundur


1 Answers

Given a straight line y = mx + n, it intercepts the x-axis when y=0.

0 = xm + n  --> x = -n/m

So the x-intercept will be -n/m.

Given two points (x_1,y_1), (x_2,y_2), you can find the slope and the y-intercept like this:

m = (y_2-y_1)/(x_2-x_1)
n = -x_1*(y_2-y_1)/(x_2-x_1) + y_1

Then, the x-intercept will be

x_1 - y_1*(x_2-x_1)/(y_2-y_1)

In JavaScript,

function x_intercept(a, b) {
  return a[0] - a[1]*(b[0]-a[0])/(b[1]-a[1]);
}
x_intercept([5, 3], [3, 4]); // 11

enter image description here

like image 158
Oriol Avatar answered Sep 05 '26 00:09

Oriol