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
function y ( x ) { return 1 / ( 1 + x * x ) ; } function trapezoidal ( a , b , n ) { let h = ( b - a ) / n ; let s = y ( a ) + y ( b ) ; for ( let i = 1 ; i < n ; i ++ ) s += 2 * y ( a + i * h ) ; return ( h / 2 ) * s ; } let x0 = 0 ; let xn = 1 ; let n = 6 ; document . write ( " " + Math . round ( trapezoidal ( x0 , xn , n ) * 10000.0 ) / 10000.0 ) ;