获取已知两点的直线上某一点的函数

3

给定两个点:

const point1 = {x: 100, y: 0.95}
const point2 = {x: 75, y: 1.05}

我需要知道当x等于某个任意值时y的值。
请假设存在线性关系。
例如,当x为80时,y是多少?当x为70时,y是多少?
是否有可以用于此的函数?
目前,我被数学解释所困扰,最好能够提供一个JavaScript或jQuery函数,当给出任意x值时返回y值。

{75,1.05},{50,1.15},{25,1.25}{0,1.35}{90,0.99} - Alive to die - Anant
所有答案都是正确的,所以每个人都加一分。也同样适用于问题。 - Alive to die - Anant
3个回答

5

当然,一条直线的斜率是指每单位 x 增加时,y 的增量。例如,如果每 2 个 x 增加 5,那么该直线的斜率为 2.5。

可以通过两点计算出其斜率:

var gradient = (point2.y - point1.y) / (point2.x - point1.x);

一条直线与y轴相交的点称为截距。可以通过以下方式从一个点计算:

var intercept = point1.y - (gradient * point1.x);

任何 x 值的 y 值都可以计算出来:
var x = 10;
var y = gradient * x + intercept;

一个结合这些东西的函数可能看起来像这样:
function yFromX(point1, point2, x) {
  var gradient = (point2.y - point1.y) / (point2.x - point1.x);
  var intercept = point1.y - (gradient * point1.x);
  return gradient * x + intercept;
}

感谢您的出色回答+1,但是您的代码中有一个错别字...您写成了point1.y=x...应该是point1.x...非常清晰的代码,变量名使用得很好...非常感谢...附言:如果您修复这个问题,我会接受这个答案。 - danday74

4
const point1 = {x: 100, y: 0.95}
const point2 = {x: 75, y: 1.05}

function getY (x) {
    var gradient = (point1.y - point2.y)/(point1.x - point2.x);
    return point1.y + gradient * (x - point1.x);
}

alert(getY(90));

3

calculate m(gradient) and c(offset) using the two points given and then use these points to calculate y for any x.

const point1 = {x: 100, y: 0.95}
const point2 = {x: 75, y: 1.05}

var m = (point1.y - point2.y) / (point1.x - point2.x);   // gradient formula 
var c = point1.y - m*point1.x;        // offset formula

function findY(x){
  return m*x + c;
}

console.log(findY(80));
console.log(findY(70));


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接