Reputation: 15683
This curve is drawn from a numpy array
I calculate the area under the curve (between 0 and the entire curve by
np.trapz(y)
How can I calculate the areas under the curve in two regions separately:
Upvotes: 0
Views: 4125
Reputation: 28253
You can pre select the range that you want to integrate over and then pass the x & y vectors to np.trapz
example:
xs = xs = np.arange(0, np.pi, np.pi/100000)
ys = np.sin(xs)
np.trapz(ys, xs)
# 1.9999999998355067 ~ 2
np.trapz(ys[xs<np.pi/2], xs[xs<np.pi/2])
# 0.999999999917753 ~ 1
cond = (xs>=np.pi/4) & (xs<3*np.pi/4)
np.trapz(ys[cond], xs[cond])
# 1.4141913474931518 ~ sqrt(2)
In your particular case:
assuming the functions are as such:
xs = np.arange(0,1,0.000001)
ys = 0.6 + xs**2
between 0 and the curve if y<1
np.trapz(ys[ys<1], xs[ys<1])
# 0.46380019145797086
between 1.0 and the curve if y>1
Here, calculate the area under the curve for y>1
and then subtract the area under the vertical line at y=1
i1 = np.trapz(ys[ys>1], xs[ys>1])
ys2 = np.ones(np.sum(ys>1))
i2 = np.trapz(ys2, xs[ys>1])
i1 - i2
# 0.10198754187656967
Alternatively, as a one-liner:
np.trapz(ys[ys>1]-1, xs[ys>1])
# 0.10198754187656967
Upvotes: 2
Reputation: 1646
you just pass the part of the array that answers your condition to trapz:
np.trapz([i for i in y if i < 1])
and lower the curve by one
np.trapz([i - 1 for i in y if i > 1])
Upvotes: 1