Shagun Chhikara
Shagun Chhikara

Reputation: 155

Python Integration Trapezoid function with Threshold

I'm having trouble writing a GENERALLY RECURSIVE function that consumes three non-negative float numbers xlo, xhi, and threshold that follow the above idea, and produces the integral for f=5x5-10x4+5x2+30 between xlo and xhi while solved numerically.

If xlo and xhi are "close enough", we can stop and approximate the shape under the curve. A trapezoid is good and simple approximation. One simple definition of "close enough" is some fixed x-distance threshold, e.g., 0.0001.

The area of a trapezoid is given to be A = ½ * h * (b1 + b2)

So far I know that the the function divides the xlo-xhi range into two ranges xlo-mid and mid-xhi then continue recursively on each half... you stop when the current xli-xhi for each part is less than the threshold. When the current xli-xhi for each part is less than the threshold, then we calculate the area of a trapezoid.

I'm not quite sure how to write a recursive function for this problem WITHOUT any loops or iteration.

Upvotes: 0

Views: 495

Answers (1)

moreON
moreON

Reputation: 2008

Something like this?

def trap(xlo, xhi, e):
    diff = xhi-xlo
    if diff > e :
        return trap(xlo,xlo+diff/2) + trap(xlo+diff/2,xhi)
    #actually calculate the trapezoidal area here.
    ...
    return result

Upvotes: 1

Related Questions