Given two lists, how can I compute the area between their plots? (the blue region in the image below).
The horizontal distance between points in the list can be assumed to be 1, as done by ListPlot
automatically in the example image.
For my use case, performance is really important so I would prefer a method that does not require doing any plotting.
Edit, solution chosen:
I finally went with this compilated version of the accepted version, which is very fast, at least on my tests:
BlocksAreaC = Compile[{{x, _Real, 2}},
Block[
{
diff = x[[2]] - x[[1]],
c = (-x[[1, 1]] + x[[2, 1]])
},
If[
Times @@ Sign[diff] == 1,
Total[Abs[diff]]/2,
If[c == 0, 0,
With[
{h = c/(-x[[1, 1]] + x[[1, 2]] + x[[2, 1]] - x[[2, 2]])},
Total[Abs[diff]*{h, 1 - h}/2]
]
]
]
],
Parallelization -> True, RuntimeAttributes -> {Listable},
CompilationTarget -> "C", RuntimeOptions -> "Speed",
CompilationOptions -> {"ExpressionOptimization" -> True,
"InlineCompiledFunctions" -> True,
"InlineExternalDefinitions" -> True}
];
areaBetweenLists7C = Compile[{{l1, _Real, 1}, {l2, _Real, 1}},
Module[
{
s1 = Partition[l1, 2, 1],
s2 = Partition[l2, 2, 1]
},
Total[Map[BlocksAreaC, Transpose[{s1, s2}]]]
],
Parallelization -> True, RuntimeAttributes -> {Listable},
CompilationTarget -> "C", RuntimeOptions -> "Speed",
CompilationOptions -> {"ExpressionOptimization" -> True,
"InlineCompiledFunctions" -> True,
"InlineExternalDefinitions" -> True}
];