How to calculate a surface between a continuous array and a line between the first and the last value?

Hi!I have an array of y-axis values continuously distributed over a timebased x-axis. If I now draw a line between the first and the last y-value, how can I calculate the green upper surfaces and then subtract the red lower surfaces? (See attached Screenshot. Ignore the vertical line lengths, just interpret it as single point values)

Screenshot_2

I just need a code reference in javascript, python or C++ … so I get the principle.

Thanks!
Sascha

Why do the greens and then the reds?

If you want a principle, you should be looking for the logic, not the code.

No offense, but I don’t know you, so if I ask for ‘childish’ things, humor me.

  1. What’s the equation for your line, f(x) ?
  2. For any two given points, (x1,y1), (x2,y2), what is the area enclosed by them and the line from (1)? (Hint: What shape will this make?)
  3. Given an array of X,Y positions, how would you go about finding a total area?

That’s your principle.

You will either have a series of data points for that chart, or a formula to derive those data points.

If you have a formula then you can use calculus technique called integration to get the area under the graph. When there are values above and below the x-axis, the negative values below it are automatically subtracted from the positive values above it.

If instead you have a series of data points that has no formula, then we can investigate other solutions that you can apply.

Thanks for your answers! I found what I was looking for:

var dx = 1 // or the distance between x points
var A=0 // Area
for i=x1 to x2 step dx{
y = [(y2-y1) / (x2-x1) ] * x(i) // the y point on line for current x value
if y(i)<y then A = A - dx*(y(i)-y) // red
if y(i)>y then A = A + dx*(y-y(i)) // green
}

That works for me!

1 Like

That’s… not actually correct, but… alright, if it works for you.

EDIT: To be precise, what you’ve done is ‘correct’, but has rounding errors in it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.