Trapezoidal Rule for Approximate Value of Definite Integral | A sample function whose definite integral 's approximate value is computed using Trapezoidal rule ; Declaring the function f ( x ) = 1 / ( 1 + x * x ) ; Function to evaluate the value of integral ; Grid spacing ; Computing sum of first and last terms in above formula ; Adding middle terms in above formula ; h / 2 indicates ( b - a ) / 2 n . Multiplying h / 2 with s . ; Range of definite integral ; Number of grids . Higher value means more accuracy
def y ( x ) : NEW_LINE INDENT return ( 1 / ( 1 + x * x ) ) NEW_LINE DEDENT def trapezoidal ( a , b , n ) : NEW_LINE INDENT h = ( b - a ) / n NEW_LINE s = ( y ( a ) + y ( b ) ) NEW_LINE i = 1 NEW_LINE while i < n : NEW_LINE INDENT s += 2 * y ( a + i * h ) NEW_LINE i += 1 NEW_LINE DEDENT return ( ( h / 2 ) * s ) NEW_LINE DEDENT x0 = 0 NEW_LINE xn = 1 NEW_LINE n = 6 NEW_LINE print ( " Value ▁ of ▁ integral ▁ is ▁ " , " % .4f " % trapezoidal ( x0 , xn , n ) ) NEW_LINE