n88b
n88b

Reputation: 153

Python: How to integrate a math function using only math module?

Just started learning python, and was asked to define a python function that integrate a math function.

We were instructed that the python function must be in the following form: (for example, to calculate the area of y = 2x + 3 between x=1 and x=2 )

integrate( 2 * x + 3, 1, 2 )

(it should return the area below)

and we are not allowed to use/import any libraries other than math (and the built in integration tool is not allowed either).

Any idea how I should go about it? When I wrote the program, I always get x is undefined, but if I define x as a value ( lets say 0 ) then the 2*x+3 part in the parameters is always taken as a value instead of a math equation, so I can't really use it inside?

It would be very helpful, not just to this assignment, but many in the future if I know how a python function can take a math equation as parameter, so thanks alot.

Upvotes: 1

Views: 8505

Answers (2)

PM 2Ring
PM 2Ring

Reputation: 55489

Let's say your integration function looks like this:

def integrate(func, lo_x, hi_x):
    #... Stuff to perform the integral, which will need to evaluate
    # the passed function for various values of x, like this
    y = func(x)
    #... more stuff
    return value

Then you can call it like this:

value = integrate(lambda x: 2 * x + 3, 1, 2)

edit

However, if the call to the integration function has to look exactly like

integrate( 2 * x + 3, 1, 2 )

then things are a bit trickier. If you know that the function is only going to be called with a polynomial function you could do it by making x an instance of a polynomial class, as suggested by M. Arthur Vaïsse in his answer.

Or, if the integrate( 2 * x + 3, 1, 2 ) comes from a string, eg from a command line argument or a raw_input() call, then you could extract the 2 * x + 3 (or whatever) from the string using standard Python string methods and then build a lambda function from that using exec.

Upvotes: 4

Arthur Vaïsse
Arthur Vaïsse

Reputation: 1571

Here come an implementation that fill the needs I think. It allow you to define mathematical function such as 2x+3 and propose an implementation of integral calculation by step as described here [http://en.wikipedia.org/wiki/Darboux_integral]

import math

class PolynomialEquation():
    """ Allow to create function that are polynomial """
    def __init__(self,coef):
        """ 
        coef : coeficients of the polynome.

        An equation initialized with [1,2,3] as parameters is equivalent to:
            y = 1 + 2X + 3X²

        """
        self.coef = coef

    def __call__(self, x):
        """
        Make the object callable like a function.
        Return the value of the equation for x
        """
        return sum( [self.coef[i]*(x**i) for i in range(len(self.coef)) ])

def step_integration(function, start, end, steps=100):
    """ 
    Proceed to a step integration of the function.
    The more steps there are, the more the approximation is good.
    """
    step_size = (end-start)/steps
    values = [start + i*step_size for i in range(1,steps+1)]
    return sum([math.fabs(function(value)*step_size) for value in values])


if __name__ == "__main__":
    #check that PolynomialEquation.value works properly. Assert make the program crash if the test is False.

    #y = 2x+3 -> y = 3+2x -> PolynomialEquation([3,2])
    eq = PolynomialEquation([3,2])
    assert eq(0) == 3
    assert eq(1) == 5
    assert eq(2) == 7

    #y = 1 + 2X + 3X² -> PolynomialEquation([1,2,3])
    eq2 = PolynomialEquation([1,2,3])
    assert eq2(0) == 1
    assert eq2(1) == 6
    assert eq2(2) == 17

    print(step_integration(eq, 0, 10))
    print(step_integration(math.sin, 0, 10))

EDIT : in truth the implementation is only the upper Darboux integral. The true Darboux integral could be computed if really needed by computing the lower Darboux integral ( replace range(1, steps+1) by range(steps) in step_integration function give you the lower Darboux function. And then increase the step parameter while the difference between the two Darboux function is greater than a small value depending on your precision need (could be 0.001 for example). Thus a 100 step integration is suppose to give you a decent approximation of the integral value.

Upvotes: 2

Related Questions