得到两点得到x截距

Sig*_*dur 1 javascript linear-regression

这可能是一个有点简单的问题,但我似乎无法让它工作.

我想找到给出两点的x截距.

让我说我有这两点:(5,3)和(3,4)我想找到x截距.目前这就是我所拥有的.哪个正确找到了y截距.在这种情况下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);
Run Code Online (Sandbox Code Playgroud)

Ori*_*iol 6

给定一条直线y = mx + n,它截取x轴时y=0.

0 = xm + n  --> x = -n/m
Run Code Online (Sandbox Code Playgroud)

所以x截距将是-n/m.

给定两点(x_1,y_1), (x_2,y_2),你可以找到斜率和y截距,如下所示:

m = (y_2-y_1)/(x_2-x_1)
n = -x_1*(y_2-y_1)/(x_2-x_1) + y_1
Run Code Online (Sandbox Code Playgroud)

然后,x截距将是

x_1 - y_1*(x_2-x_1)/(y_2-y_1)
Run Code Online (Sandbox Code Playgroud)

在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
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


afu*_*ous 5

function xIntercept(a, m) {
    return a[0] - a[1] / m;
}
Run Code Online (Sandbox Code Playgroud)

我建议您将点表示为{x: 5, y: 3}而不是[5, 3]因为它使代码的其余部分更加清晰。