danday74
danday74

Reputation: 57223

Function to get point on line where two points are known

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.

Upvotes: 3

Views: 828

Answers (3)

Seb Morris
Seb Morris

Reputation: 390

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 combines 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;
}

Upvotes: 5

Dij
Dij

Reputation: 9808

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

Upvotes: 3

Ned Howley
Ned Howley

Reputation: 868

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

Upvotes: 4

Related Questions