简体   繁体   中英

How to calculate separate areas under a curve in Numpy

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:

  • between 0 and the curve if y<1
  • between 1.0 and the curve if y>1

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM