Search code examples
pythonnumpylinearea

Find the area between two curves separately in numpy


I have in a list of points two different curves (y1, y2) and I want to find the area between the curves when:

  • y1 > y2
  • y1 < y2

I have found this post, but it only calculates the sum of both areas.

If we plot what I want, I want separately the blue area and the red area.

separately


Solution

  • Edit: I noticed in hindsight, that this solution is not exact and there are probably cases where it doesn't work at all. As long as there is no other better answer I will leave this here.

    You can use

    diff = y1 - y2 # calculate difference
    posPart = np.maximum(diff, 0) # only keep positive part, set other values to zero
    negPart = -np.minimum(diff, 0) # only keep negative part, set other values to zero
    

    to seperate the blue from the red part. Then calculate their areas with np.trapz:

    posArea = np.trapz(posPart)
    negArea = np.trapz(negPart)