Trapezoidal Rule for Approximate Value of Definite Integral
In the field of numerical analysis, Trapezoidal rule is used to find the approximation of a definite integral. The basic idea in Trapezoidal rule is to assume the region under the graph of the given function to be a trapezoid and calculate its area.
It follows that:
For more accurate results the domain of the graph is divided into n segments of equal size as shown below:
Grid spacing or segment size h = (b-a) / n.
Therefore, approximate value of the integral can be given by:
C++
#include<stdio.h>
float y( float x)
{
return 1/(1+x*x);
}
float trapezoidal( float a, float b, float n)
{
float h = (b-a)/n;
float s = y(a)+y(b);
for ( int i = 1; i < n; i++)
s += 2*y(a+i*h);
return (h/2)*s;
}
int main()
{
float x0 = 0;
float xn = 1;
int n = 6;
printf ( "Value of integral is %6.4f\n" ,
trapezoidal(x0, xn, n));
return 0;
}
|
Java
class GFG
{
static float y( float x)
{
return 1 / ( 1 + x * x);
}
static float trapezoidal( float a, float b, float n)
{
float h = (b - a) / n;
float s = y(a) + y(b);
for ( int i = 1 ; i < n; i++)
s += 2 * y( a + i * h);
return (h / 2 ) * s;
}
public static void main (String[] args)
{
float x0 = 0 ;
float xn = 1 ;
int n = 6 ;
System.out.println( "Value of integral is " +
Math.round(trapezoidal(x0, xn, n)
* 10000.0 ) / 10000.0 );
}
}
|
Python3
def y( x ):
return ( 1 / ( 1 + x * x))
def trapezoidal (a, b, n):
h = (b - a) / n
s = (y(a) + y(b))
i = 1
while i < n:
s + = 2 * y(a + i * h)
i + = 1
return ((h / 2 ) * s)
x0 = 0
xn = 1
n = 6
print ( "Value of integral is " ,
"%.4f" % trapezoidal(x0, xn, n))
|
C#
using System;
class GFG {
static float y( float x)
{
return 1 / (1 + x * x);
}
static float trapezoidal( float a,
float b, float n)
{
float h = (b - a) / n;
float s = y(a) + y(b);
for ( int i = 1; i < n; i++)
s += 2 * y( a + i * h);
return (h / 2) * s;
}
public static void Main ()
{
float x0 = 0;
float xn = 1;
int n = 6;
Console.Write( "Value of integral is "
+ Math.Round(trapezoidal(x0, xn, n)
* 10000.0) / 10000.0);
}
}
|
PHP
<?php
function y( $x )
{
return 1 / (1 + $x * $x );
}
function trapezoidal( $a , $b , $n )
{
$h = ( $b - $a ) / $n ;
$s = y( $a ) + y( $b );
for ( $i = 1; $i < $n ; $i ++)
$s += 2 * Y( $a + $i * $h );
return ( $h / 2) * $s ;
}
$x0 = 0;
$xn = 1;
$n = 6;
echo ( "Value of integral is " );
echo (trapezoidal( $x0 , $xn , $n ));
?>
|
Javascript
<script>
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( "Value of integral is " +
Math.round(trapezoidal(x0, xn, n) *
10000.0) / 10000.0);
</script>
|
Output:
Value of integral is 0.7842
References:
https://en.wikipedia.org/wiki/Trapezoidal_rule
Last Updated :
11 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...