pythonpolynomialspolynomial-mathcalculus

Integral of a Polynomial in Python


How would we write a function in python that returns the definite integral of a polynomial between two points (X_1 and X_2)?

The function takes 3 arguments:

We are given the formula for the definite integral of a polynomial such as We are given the formula for the definite integral of a polynomial such as

My attempt at this function is below, however the output returns 0.2

    def take_integral(A, X_1, X_2):

            integral = 0

            for i in range(len(A)):
                integral = A*(X_2**(i+1) - X_1**(i+1))/(i+1)
            return integral

    print(take_integral([1, 2, 1], 0, 3))

The expected result from the function should be:


    print(take_integral([1, 2, 1], 0, 3))
    21.0
    print(take_integral([5, 0, 0, -2, 1], 0, 1))
    1.0

Solution

  • A few points here:

    Here's the code that will give you the right answers:

    def take_integral(A, X_1, X_2):
    
            integral = 0
    
            for i in range(len(A)):
                integral += A[i]*(X_2**((len(A))-i) - X_1**((len(A))-i))/((len(A))-i)
            return integral
    
    print(take_integral([1, 2, 1], 0, 3))
    21
    print(take_integral([5, 0, 0, -2, 1], 0, 1))
    1