admin管理员组

文章数量:1406937

Given two points:

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

I need to know the value of y when x equals some arbitrary value.

Please assume a linear relationship exists.

For example, what is y when x is 80? what is y when x is 70?

Is there a function that I could use for this?

Currently I've been confused by mathematical explanations and would ideally like a JavaScript or jQuery function that, when given an arbitrary x value returns the y value.

Given two points:

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

I need to know the value of y when x equals some arbitrary value.

Please assume a linear relationship exists.

For example, what is y when x is 80? what is y when x is 70?

Is there a function that I could use for this?

Currently I've been confused by mathematical explanations and would ideally like a JavaScript or jQuery function that, when given an arbitrary x value returns the y value.

Share edited Feb 9, 2018 at 10:40 halfer 20.4k19 gold badges109 silver badges202 bronze badges asked Aug 2, 2017 at 16:38 danday74danday74 57.5k55 gold badges269 silver badges333 bronze badges 2
  • something like :- {75,1.05},{50,1.15},{25,1.25}{0,1.35}{90,0.99} – Death-is-the-real-truth Commented Aug 2, 2017 at 16:47
  • All answers are correct so +1 to every-one.As well as to question to – Death-is-the-real-truth Commented Aug 2, 2017 at 16:49
Add a ment  | 

3 Answers 3

Reset to default 5

Sure, the gradient of a line is the amount y increases for every unit x increases. E.g. if y goes up 5 for every 2 x goes up, the line is said to have a gradient of 2.5.

The gradient can be calculated from 2 points like so:

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

The intercept of a line is the y value it crosses the y axis at. It can be calculated from 1 point like so:

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

The y value for any x value can then be calculated:

var x = 10;
var y = gradient * x + intercept;

A function which bines these things might look like:

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));

本文标签: javascriptFunction to get point on line where two points are knownStack Overflow