给定两个点:
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值。
给定两个点:
const point1 = {x: 100, y: 0.95}
const point2 = {x: 75, y: 1.05}
当然,一条直线的斜率是指每单位 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;
}
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));
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));