python-3.xnumpynumerical-integration

calculate the absolute area from a graph that also gets negative


I want to calculate the absolute area under the given graph. What now happens is that it just integrates the line f. This line also gets negative. I am integrating from -5 to 5.

How can I adjust the function so it will give the absolute value?

edit: Something else I would like to know is how to calculate the area only where f(x) >0? Is there an option to do a double integral easily?

from numpy import *
import matplotlib.pyplot as plt

x = arange(-5,5.001,0.00001)
f = cos(4*x+1)**2 *(6 - 0.5* x**2)

print(trapz(f,x))
plt.plot([-5,5],[0,0])
plt.plot(x,f)
plt.show()

Solution

  • You can use numpy.abs(..) [numpy-doc] to calculate the element-wise absolute value for the array of values.

    So we can calculate the values for f with:

    f_abs = np.abs(f)
    print(trapz(f_abs,x))

    This will then calculate an approximation of the area, and thus consider the area under the x-axis to be positive as well.

    If you want to ignore the negative parts, you can set negative values to 0 with numpy.clip(..) [numpy-doc]:

    print(trapz(f.clip(min=0),x))