(1)Left-point rectangular rule
#include <stdio.h>
#include <math.h>
double f(double x)
{return exp(-x*x) ; }
int main()
{
int i, n;
double a=0.0, b=1.0, h, s=0.0 , x ;
printf("Enter n=");
scanf("%d", &n);
h = (b-a)/n ;
for (i= 0;i<n;i++)
s = s + f(a + i*h) ;
s=s*h ;
printf("Result =%lf\n", s) ;
return 0;
}
C:\gcc-2.95.2>a
Enter n=1000
Result =0.747140
C:\gcc-2.95.2>a
Enter n=10000
Result =0.746856
C:\gcc-2.95.2>a
Enter n=100000
Result =0.746827
C:\gcc-2.95.2>a
Enter n=1000000
Result =0.746824
C:\gcc-2.95.2>a
Enter n=500000
Result =0.746825
C:\gcc-2.95.2>a
Enter n=700000
Result =0.746825
C:\gcc-2.95.2>a
Enter n=900000
Result =0.746824
(2) Mid-point rectangular rule
/* Rectangular rule */
#include <stdio.h>
#include <math.h>
double f(double x)
{return exp(-x*x) ; }
int main()
{
int i, n;
double a=0.0, b=1.0, h, s=0.0 , x ;
printf("Number of partitions = ");
scanf("%d", &n) ;
h = (b-a)/n ;
for (i= 0;i<n;i++) s = s + f(h/2 + i*h) ;
s=s*h ;
printf("Result =%f\n", s) ;
return 0;
}
C:\gcc-2.95.2>mid
Number of partitions = 200
Result =0.746825
C:\gcc-2.95.2>mid
Number of partitions = 300
Result =0.746824
C:\gcc-2.95.2>mid
Number of partitions = 290
Result =0.746824
C:\gcc-2.95.2>mid
Number of partitions = 260
Result =0.746825
C:\gcc-2.95.2>mid
Number of partitions = 270
Result =0.746825
C:\gcc-2.95.2>mid
Number of partitions = 280
Result =0.746825
C:\gcc-2.95.2>mid
Number of partitions = 290
Result =0.746824
(3) Trapezoidal rule
/* Trapezoidal rule */
#include <stdio.h>
#include <math.h>
double f(double x)
{return exp(-x*x);}
int main()
{
int i, n ;
double a=0.0, b=1.0 , h, s=0.0, x;
printf("Enter number of partitions = ");
scanf("%d", &n) ;
h = (b-a)/n ;
for (i=1;i<=n-1;i++) s = s + f(a + i*h);
s=h/2*(f(a)+f(b))+ h* s;
printf("%f\n", s) ;
return 0;
}
C:\gcc-2.95.2>gcc trap.c -o trap
C:\gcc-2.95.2>trap
Enter number of partitions = 200
0.746823
C:\gcc-2.95.2>trap
Enter number of partitions = 300
0.746823
C:\gcc-2.95.2>trap
Enter number of partitions = 320
0.746824
C:\gcc-2.95.2>trap
Enter number of partitions = 310
0.746823