Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the area underneath a mathematical function

I have a range of data that I have approximated using a polynomial of degree 2 in Python. I want to calculate the area underneath this polynomial between 0 and 1.

Is there a calculus, or similar package from numpy that I can use, or should I just make a simple function to integrate these functions?

I'm a little unclear what the best approach for defining mathematical functions is.

Thanks.

like image 848
djq Avatar asked Dec 01 '22 06:12

djq


1 Answers

If you're integrating only polynomials, you don't need to represent a general mathematical function, use numpy.poly1d, which has an integ method for integration.

>>> import numpy
>>> p = numpy.poly1d([2, 4, 6])
>>> print p
   2
2 x + 4 x + 6
>>> i = p.integ()
>>> i
poly1d([ 0.66666667,  2.        ,  6.        ,  0.        ])
>>> integrand = i(1) - i(0) # Use call notation to evaluate a poly1d
>>> integrand
8.6666666666666661

For integrating arbitrary numerical functions, you would use scipy.integrate with normal Python functions for functions. For integrating functions analytically, you would use sympy. It doesn't sound like you want either in this case, especially not the latter.

like image 113
Mike Graham Avatar answered Dec 05 '22 07:12

Mike Graham